@naeemo/capnp 0.8.1 → 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/dist/cli.js CHANGED
@@ -1,1802 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  #!/usr/bin/env node
3
- import { execSync } from "node:child_process";
4
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
- import { tmpdir } from "node:os";
6
- import { basename, dirname, join } from "node:path";
7
3
  import { parseArgs } from "node:util";
8
4
 
9
- //#region src/codegen/generator.ts
10
- const DEFAULT_OPTIONS = { runtimeImportPath: "@naeemo/capnp" };
5
+ //#region src/cli-unified.ts
11
6
  /**
12
- * CodeGeneratorRequest 生成 TypeScript 代码
13
- */
14
- function generateFromRequest(request, options) {
15
- const opts = {
16
- ...DEFAULT_OPTIONS,
17
- ...options
18
- };
19
- const files = /* @__PURE__ */ new Map();
20
- const nodes = request.nodes;
21
- const requestedFiles = request.requestedFiles;
22
- for (const file of requestedFiles) {
23
- const filename = file.filename.replace(/\.capnp$/, ".ts");
24
- const code = generateFile(file.id, nodes, opts);
25
- files.set(filename, code);
26
- }
27
- return files;
28
- }
29
- /**
30
- * 生成单个文件的 TypeScript 代码
31
- */
32
- function generateFile(fileId, allNodes, options) {
33
- const lines = [];
34
- lines.push("// Generated by @naeemo/capnp");
35
- lines.push("// DO NOT EDIT MANUALLY");
36
- lines.push("");
37
- lines.push(`import { MessageReader, MessageBuilder, StructReader, StructBuilder, createUnionReader, createUnionBuilder } from "${options.runtimeImportPath}";`);
38
- lines.push("");
39
- lines.push("// XOR helpers for default value encoding");
40
- lines.push("function xorFloat32(a: number, b: number): number {");
41
- lines.push(" const view = new DataView(new ArrayBuffer(4));");
42
- lines.push(" view.setFloat32(0, a, true);");
43
- lines.push(" const aBits = view.getUint32(0, true);");
44
- lines.push(" view.setFloat32(0, b, true);");
45
- lines.push(" const bBits = view.getUint32(0, true);");
46
- lines.push(" view.setUint32(0, aBits ^ bBits, true);");
47
- lines.push(" return view.getFloat32(0, true);");
48
- lines.push("}");
49
- lines.push("");
50
- lines.push("function xorFloat64(a: number, b: number): number {");
51
- lines.push(" const view = new DataView(new ArrayBuffer(8));");
52
- lines.push(" view.setFloat64(0, a, true);");
53
- lines.push(" const aBits = view.getBigUint64(0, true);");
54
- lines.push(" view.setFloat64(0, b, true);");
55
- lines.push(" const bBits = view.getBigUint64(0, true);");
56
- lines.push(" view.setBigUint64(0, aBits ^ bBits, true);");
57
- lines.push(" return view.getFloat64(0, true);");
58
- lines.push("}");
59
- lines.push("");
60
- let filePrefix = "";
61
- try {
62
- filePrefix = allNodes.find((n) => n.id === fileId)?.displayName || "";
63
- } catch (_e) {}
64
- const fileNodes = allNodes.filter((n) => {
65
- try {
66
- if (n.scopeId === fileId) return true;
67
- if (n.scopeId === 0n && filePrefix && n.displayName.startsWith(`${filePrefix}:`)) return n.displayName.substring(filePrefix.length + 1).includes("$");
68
- } catch (_e) {}
69
- return false;
70
- });
71
- for (const node of fileNodes) {
72
- if (node.isStruct) lines.push(generateStruct(node, allNodes));
73
- else if (node.isEnum) lines.push(generateEnum(node));
74
- else if (node.isInterface) lines.push(generateInterface(node, allNodes));
75
- lines.push("");
76
- }
77
- return lines.join("\n");
78
- }
79
- /**
80
- * 生成 Struct 的 TypeScript 代码
81
- */
82
- function generateStruct(node, allNodes) {
83
- const lines = [];
84
- const structName = getShortName(node.displayName);
85
- let unionGroups = [];
86
- let regularFields = [];
87
- let groupFields = [];
88
- try {
89
- const analysis = analyzeFields(node, allNodes);
90
- unionGroups = analysis.unionGroups;
91
- regularFields = analysis.regularFields;
92
- groupFields = analysis.groupFields;
93
- } catch (_e) {
94
- lines.push(`export interface ${structName} {`);
95
- lines.push(" // Note: Could not parse struct fields");
96
- lines.push("}");
97
- lines.push("");
98
- lines.push(`export class ${structName}Reader {`);
99
- lines.push(" constructor(private reader: StructReader) {}");
100
- lines.push("}");
101
- lines.push("");
102
- lines.push(`export class ${structName}Builder {`);
103
- lines.push(" constructor(private builder: StructBuilder) {}");
104
- lines.push("}");
105
- return lines.join("\n");
106
- }
107
- lines.push(`export interface ${structName} {`);
108
- for (const field of regularFields) {
109
- if (!field.isSlot) continue;
110
- const tsType = getTypeScriptType(field.slotType, allNodes);
111
- lines.push(` ${field.name}: ${tsType};`);
112
- }
113
- for (const { field: groupField, groupNode } of groupFields) {
114
- const groupName = groupField.name;
115
- try {
116
- for (const field of groupNode.structFields) {
117
- if (!field.isSlot) continue;
118
- const tsType = getTypeScriptType(field.slotType, allNodes);
119
- lines.push(` ${groupName}${capitalize(field.name)}: ${tsType};`);
120
- }
121
- } catch (_e) {}
122
- }
123
- for (const [groupIndex, group] of unionGroups.entries()) {
124
- const unionName = group.fields.length > 0 ? `${capitalize(group.fields[0].name)}Union` : `Union${groupIndex}`;
125
- lines.push(` ${unionName}: ${generateUnionVariantType(group, allNodes)};`);
126
- }
127
- lines.push("}");
128
- lines.push("");
129
- lines.push(`export class ${structName}Reader {`);
130
- lines.push(" constructor(private reader: StructReader) {}");
131
- lines.push("");
132
- for (const field of regularFields) {
133
- if (!field.isSlot) continue;
134
- const getter = generateFieldGetter(field);
135
- lines.push(` ${getter}`);
136
- lines.push("");
137
- }
138
- for (const { field: groupField, groupNode } of groupFields) {
139
- const groupName = groupField.name;
140
- try {
141
- for (const field of groupNode.structFields) {
142
- if (!field.isSlot) continue;
143
- const getter = generateGroupFieldGetter(field, groupName);
144
- lines.push(` ${getter}`);
145
- lines.push("");
146
- }
147
- } catch (_e) {}
148
- }
149
- for (const [groupIndex, group] of unionGroups.entries()) {
150
- const unionName = group.fields.length > 0 ? `${capitalize(group.fields[0].name)}Union` : `Union${groupIndex}`;
151
- const variants = {};
152
- for (const field of group.fields) variants[field.discriminantValue] = field.name;
153
- const variantsStr = JSON.stringify(variants).replace(/"/g, "'");
154
- lines.push(` get${unionName}Tag(): number {`);
155
- lines.push(` return this.reader.getUint16(${group.discriminantOffset * 2});`);
156
- lines.push(" }");
157
- lines.push("");
158
- lines.push(` get${unionName}Variant(): string | undefined {`);
159
- lines.push(` const tag = this.get${unionName}Tag();`);
160
- lines.push(` const variants = ${variantsStr};`);
161
- lines.push(" return variants[tag];");
162
- lines.push(" }");
163
- lines.push("");
164
- for (const field of group.fields) {
165
- const getter = generateUnionFieldGetter(field, unionName, field.discriminantValue);
166
- lines.push(` ${getter}`);
167
- lines.push("");
168
- }
169
- for (const field of group.fields) {
170
- const setter = generateUnionFieldSetter(field, unionName, field.discriminantValue, group.discriminantOffset * 2);
171
- lines.push(` ${setter}`);
172
- lines.push("");
173
- }
174
- }
175
- lines.push("}");
176
- lines.push("");
177
- lines.push(`export class ${structName}Builder {`);
178
- lines.push(" constructor(private builder: StructBuilder) {}");
179
- lines.push("");
180
- for (const field of regularFields) {
181
- if (!field.isSlot) continue;
182
- const setter = generateFieldSetter(field);
183
- lines.push(` ${setter}`);
184
- lines.push("");
185
- }
186
- for (const { field: groupField, groupNode } of groupFields) {
187
- const groupName = groupField.name;
188
- try {
189
- for (const field of groupNode.structFields) {
190
- if (!field.isSlot) continue;
191
- const setter = generateGroupFieldSetter(field, groupName);
192
- lines.push(` ${setter}`);
193
- lines.push("");
194
- }
195
- } catch (_e) {}
196
- }
197
- for (const [groupIndex, group] of unionGroups.entries()) {
198
- const unionName = group.fields.length > 0 ? `${capitalize(group.fields[0].name)}Union` : `Union${groupIndex}`;
199
- for (const field of group.fields) {
200
- const setter = generateUnionFieldSetter(field, unionName, field.discriminantValue, group.discriminantOffset * 2);
201
- lines.push(` ${setter}`);
202
- lines.push("");
203
- }
204
- }
205
- lines.push("}");
206
- return lines.join("\n");
207
- }
208
- /**
209
- * 分析字段,分离 Union 字段和普通字段,展开 Group 字段
210
- */
211
- function analyzeFields(node, allNodes) {
212
- const fields = node.structFields;
213
- const unionGroups = /* @__PURE__ */ new Map();
214
- const regularFields = [];
215
- const groupFields = [];
216
- for (const field of fields) {
217
- if (field.isGroup) {
218
- const groupNode = allNodes.find((n) => n.id === field.groupTypeId);
219
- if (groupNode?.isStruct) groupFields.push({
220
- field,
221
- groupNode
222
- });
223
- continue;
224
- }
225
- if (node.structDiscriminantCount > 0 && field.discriminantValue !== 65535 && field.discriminantValue !== 0) {
226
- const discriminantOffset = node.structDiscriminantOffset;
227
- if (!unionGroups.has(discriminantOffset)) unionGroups.set(discriminantOffset, {
228
- discriminantOffset,
229
- fields: []
230
- });
231
- unionGroups.get(discriminantOffset).fields.push(field);
232
- } else regularFields.push(field);
233
- }
234
- return {
235
- unionGroups: Array.from(unionGroups.values()),
236
- regularFields,
237
- groupFields
238
- };
239
- }
240
- /**
241
- * 生成 Union variant 类型
242
- */
243
- function generateUnionVariantType(group, allNodes) {
244
- return group.fields.map((f) => {
245
- const tsType = f.isSlot ? getTypeScriptType(f.slotType, allNodes) : "unknown";
246
- return `{ tag: ${f.discriminantValue}; variant: '${f.name}'; value: ${tsType} }`;
247
- }).join(" | ");
248
- }
249
- /**
250
- * 生成 Union 字段的 getter
251
- */
252
- function generateUnionFieldGetter(field, unionName, discriminantValue) {
253
- const name = field.name;
254
- const type = field.slotType;
255
- if (!type || !field.isSlot) return `get${capitalize(name)}(): unknown | undefined { return this.get${unionName}Tag() === ${discriminantValue} ? undefined : undefined; }`;
256
- const returnType = getTypeScriptTypeForSetter(type);
257
- let body;
258
- switch (type.kind) {
259
- case "void":
260
- body = "return undefined;";
261
- break;
262
- case "bool":
263
- body = `return this.reader.getBool(${field.slotOffset * 8});`;
264
- break;
265
- case "int8":
266
- body = `return this.reader.getInt8(${field.slotOffset});`;
267
- break;
268
- case "int16":
269
- body = `return this.reader.getInt16(${field.slotOffset * 2});`;
270
- break;
271
- case "int32":
272
- body = `return this.reader.getInt32(${field.slotOffset * 4});`;
273
- break;
274
- case "int64":
275
- body = `return this.reader.getInt64(${field.slotOffset * 8});`;
276
- break;
277
- case "uint8":
278
- body = `return this.reader.getUint8(${field.slotOffset});`;
279
- break;
280
- case "uint16":
281
- body = `return this.reader.getUint16(${field.slotOffset * 2});`;
282
- break;
283
- case "uint32":
284
- body = `return this.reader.getUint32(${field.slotOffset * 4});`;
285
- break;
286
- case "uint64":
287
- body = `return this.reader.getUint64(${field.slotOffset * 8});`;
288
- break;
289
- case "float32":
290
- body = `return this.reader.getFloat32(${field.slotOffset * 4});`;
291
- break;
292
- case "float64":
293
- body = `return this.reader.getFloat64(${field.slotOffset * 8});`;
294
- break;
295
- case "text":
296
- body = `return this.reader.getText(${field.slotOffset});`;
297
- break;
298
- case "data":
299
- body = `return this.reader.getData(${field.slotOffset});`;
300
- break;
301
- default: body = "return undefined;";
302
- }
303
- return `get${capitalize(name)}(): ${returnType} | undefined {
304
- if (this.get${unionName}Tag() !== ${discriminantValue}) return undefined;
305
- ${body}
306
- }`;
307
- }
308
- /**
309
- * 生成 Group 字段的 getter
310
- * Group 字段在父 struct 的 data/pointer section 中,但命名空间是 Group 的名字
311
- */
312
- function generateGroupFieldGetter(field, groupName) {
313
- const name = field.name;
314
- const type = field.slotType;
315
- if (!type) return `get${capitalize(groupName)}${capitalize(name)}(): unknown { return undefined; }`;
316
- switch (type.kind) {
317
- case "void": return `get${capitalize(groupName)}${capitalize(name)}(): void { return undefined; }`;
318
- case "bool": return `get${capitalize(groupName)}${capitalize(name)}(): boolean { return this.reader.getBool(${field.slotOffset * 8}); }`;
319
- case "int8": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getInt8(${field.slotOffset}); }`;
320
- case "int16": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getInt16(${field.slotOffset * 2}); }`;
321
- case "int32": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getInt32(${field.slotOffset * 4}); }`;
322
- case "int64": return `get${capitalize(groupName)}${capitalize(name)}(): bigint { return this.reader.getInt64(${field.slotOffset * 8}); }`;
323
- case "uint8": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getUint8(${field.slotOffset}); }`;
324
- case "uint16": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getUint16(${field.slotOffset * 2}); }`;
325
- case "uint32": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getUint32(${field.slotOffset * 4}); }`;
326
- case "uint64": return `get${capitalize(groupName)}${capitalize(name)}(): bigint { return this.reader.getUint64(${field.slotOffset * 8}); }`;
327
- case "float32": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getFloat32(${field.slotOffset * 4}); }`;
328
- case "float64": return `get${capitalize(groupName)}${capitalize(name)}(): number { return this.reader.getFloat64(${field.slotOffset * 8}); }`;
329
- case "text": return `get${capitalize(groupName)}${capitalize(name)}(): string { return this.reader.getText(${field.slotOffset}); }`;
330
- case "data": return `get${capitalize(groupName)}${capitalize(name)}(): Uint8Array { return this.reader.getData(${field.slotOffset}); }`;
331
- default: return `get${capitalize(groupName)}${capitalize(name)}(): unknown { return undefined; }`;
332
- }
333
- }
334
- /**
335
- * 生成 Group 字段的 setter
336
- */
337
- function generateGroupFieldSetter(field, groupName) {
338
- const name = field.name;
339
- const type = field.slotType;
340
- const paramType = getTypeScriptTypeForSetter(type);
341
- if (!type || !field.isSlot) return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { /* TODO */ }`;
342
- switch (type.kind) {
343
- case "void": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { }`;
344
- case "bool": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setBool(${field.slotOffset * 8}, value); }`;
345
- case "int8": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setInt8(${field.slotOffset}, value); }`;
346
- case "int16": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setInt16(${field.slotOffset * 2}, value); }`;
347
- case "int32": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setInt32(${field.slotOffset * 4}, value); }`;
348
- case "int64": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setInt64(${field.slotOffset * 8}, value); }`;
349
- case "uint8": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setUint8(${field.slotOffset}, value); }`;
350
- case "uint16": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setUint16(${field.slotOffset * 2}, value); }`;
351
- case "uint32": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setUint32(${field.slotOffset * 4}, value); }`;
352
- case "uint64": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setUint64(${field.slotOffset * 8}, value); }`;
353
- case "float32": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setFloat32(${field.slotOffset * 4}, value); }`;
354
- case "float64": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setFloat64(${field.slotOffset * 8}, value); }`;
355
- case "text": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setText(${field.slotOffset}, value); }`;
356
- case "data": return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { this.builder.setData(${field.slotOffset}, value); }`;
357
- default: return `set${capitalize(groupName)}${capitalize(name)}(value: ${paramType}): void { /* TODO */ }`;
358
- }
359
- }
360
- /**
361
- * 生成 Union 字段的 setter
362
- */
363
- function generateUnionFieldSetter(field, _unionName, discriminantValue, discriminantOffset) {
364
- const name = field.name;
365
- const type = field.slotType;
366
- const paramType = getTypeScriptTypeForSetter(type);
367
- if (!type || !field.isSlot) return `set${capitalize(name)}(value: ${paramType}): void {
368
- this.builder.setUint16(${discriminantOffset}, ${discriminantValue});
369
- }`;
370
- let body;
371
- switch (type.kind) {
372
- case "void":
373
- body = "";
374
- break;
375
- case "bool":
376
- body = `this.builder.setBool(${field.slotOffset * 8}, value);`;
377
- break;
378
- case "int8":
379
- body = `this.builder.setInt8(${field.slotOffset}, value);`;
380
- break;
381
- case "int16":
382
- body = `this.builder.setInt16(${field.slotOffset * 2}, value);`;
383
- break;
384
- case "int32":
385
- body = `this.builder.setInt32(${field.slotOffset * 4}, value);`;
386
- break;
387
- case "int64":
388
- body = `this.builder.setInt64(${field.slotOffset * 8}, value);`;
389
- break;
390
- case "uint8":
391
- body = `this.builder.setUint8(${field.slotOffset}, value);`;
392
- break;
393
- case "uint16":
394
- body = `this.builder.setUint16(${field.slotOffset * 2}, value);`;
395
- break;
396
- case "uint32":
397
- body = `this.builder.setUint32(${field.slotOffset * 4}, value);`;
398
- break;
399
- case "uint64":
400
- body = `this.builder.setUint64(${field.slotOffset * 8}, value);`;
401
- break;
402
- case "float32":
403
- body = `this.builder.setFloat32(${field.slotOffset * 4}, value);`;
404
- break;
405
- case "float64":
406
- body = `this.builder.setFloat64(${field.slotOffset * 8}, value);`;
407
- break;
408
- case "text":
409
- body = `this.builder.setText(${field.slotOffset}, value);`;
410
- break;
411
- case "data":
412
- body = `this.builder.setData(${field.slotOffset}, value);`;
413
- break;
414
- default: body = "";
415
- }
416
- return `set${capitalize(name)}(value: ${paramType}): void {
417
- this.builder.setUint16(${discriminantOffset}, ${discriminantValue});
418
- ${body}
419
- }`;
420
- }
421
- /**
422
- * 从 ValueReader 提取默认值,用于代码生成
423
- */
424
- function extractDefaultValue(field) {
425
- const defaultValue = field.defaultValue;
426
- if (!defaultValue) return void 0;
427
- const type = field.slotType;
428
- if (!type) return void 0;
429
- switch (type.kind) {
430
- case "bool":
431
- if (defaultValue.isBool) return defaultValue.boolValue ? "true" : "false";
432
- return;
433
- case "int8":
434
- if (defaultValue.isInt8) return `${defaultValue.int8Value}`;
435
- return;
436
- case "int16":
437
- if (defaultValue.isInt16) return `${defaultValue.int16Value}`;
438
- return;
439
- case "int32":
440
- if (defaultValue.isInt32) return `${defaultValue.int32Value}`;
441
- return;
442
- case "int64":
443
- if (defaultValue.isInt64) return `${defaultValue.int64Value}n`;
444
- return;
445
- case "uint8":
446
- if (defaultValue.isUint8) return `${defaultValue.uint8Value}`;
447
- return;
448
- case "uint16":
449
- if (defaultValue.isUint16) return `${defaultValue.uint16Value}`;
450
- return;
451
- case "uint32":
452
- if (defaultValue.isUint32) return `${defaultValue.uint32Value}`;
453
- return;
454
- case "uint64":
455
- if (defaultValue.isUint64) return `${defaultValue.uint64Value}n`;
456
- return;
457
- case "float32":
458
- if (defaultValue.isFloat32) {
459
- const val = defaultValue.float32Value;
460
- if (Number.isNaN(val)) return "NaN";
461
- if (val === Number.POSITIVE_INFINITY) return "Infinity";
462
- if (val === Number.NEGATIVE_INFINITY) return "-Infinity";
463
- return `${val}`;
464
- }
465
- return;
466
- case "float64":
467
- if (defaultValue.isFloat64) {
468
- const val = defaultValue.float64Value;
469
- if (Number.isNaN(val)) return "NaN";
470
- if (val === Number.POSITIVE_INFINITY) return "Infinity";
471
- if (val === Number.NEGATIVE_INFINITY) return "-Infinity";
472
- return `${val}`;
473
- }
474
- return;
475
- case "enum":
476
- if (defaultValue.isEnum) return `${defaultValue.enumValue}`;
477
- return;
478
- default: return;
479
- }
480
- }
481
- /**
482
- * 生成 XOR 解码表达式(用于 getter)
483
- * stored ^ default = actual
484
- */
485
- function generateXorDecode(expr, defaultValue, typeKind) {
486
- switch (typeKind) {
487
- case "bool": return `${expr} !== ${defaultValue}`;
488
- case "int8":
489
- case "int16":
490
- case "int32": return `(${expr} ^ ${defaultValue}) | 0`;
491
- case "uint8":
492
- case "uint16":
493
- case "uint32": return `${expr} ^ ${defaultValue}`;
494
- case "int64":
495
- case "uint64": return `${expr} ^ ${defaultValue}`;
496
- case "float32": return `xorFloat32(${expr}, ${defaultValue})`;
497
- case "float64": return `xorFloat64(${expr}, ${defaultValue})`;
498
- case "enum": return `${expr} ^ ${defaultValue}`;
499
- default: return expr;
500
- }
501
- }
502
- /**
503
- * 生成 XOR 编码表达式(用于 setter)
504
- * actual ^ default = stored
505
- */
506
- function generateXorEncode(valueExpr, defaultValue, typeKind) {
507
- switch (typeKind) {
508
- case "bool": return `${valueExpr} !== ${defaultValue}`;
509
- case "int8":
510
- case "int16":
511
- case "int32": return `(${valueExpr} >>> 0) ^ ${defaultValue}`;
512
- case "uint8":
513
- case "uint16":
514
- case "uint32": return `${valueExpr} ^ ${defaultValue}`;
515
- case "int64":
516
- case "uint64": return `${valueExpr} ^ ${defaultValue}`;
517
- case "float32": return `xorFloat32(${valueExpr}, ${defaultValue})`;
518
- case "float64": return `xorFloat64(${valueExpr}, ${defaultValue})`;
519
- case "enum": return `${valueExpr} ^ ${defaultValue}`;
520
- default: return valueExpr;
521
- }
522
- }
523
- /**
524
- * 生成字段 getter
525
- */
526
- function generateFieldGetter(field) {
527
- const name = field.name;
528
- const type = field.slotType;
529
- const defaultValue = extractDefaultValue(field);
530
- if (!type) return `get ${name}(): unknown { return undefined; }`;
531
- if (defaultValue !== void 0 && type.kind !== "text" && type.kind !== "data") {
532
- const decodedExpr = generateXorDecode(`this.reader.get${capitalize(type.kind)}(${getByteOffset(field, type.kind)})`, defaultValue, type.kind);
533
- return `get ${name}(): ${getTypeScriptTypeForSetter(type)} { return ${decodedExpr}; }`;
534
- }
535
- switch (type.kind) {
536
- case "void": return `get ${name}(): void { return undefined; }`;
537
- case "bool": return `get ${name}(): boolean { return this.reader.getBool(${field.slotOffset * 8}); }`;
538
- case "int8": return `get ${name}(): number { return this.reader.getInt8(${field.slotOffset}); }`;
539
- case "int16": return `get ${name}(): number { return this.reader.getInt16(${field.slotOffset * 2}); }`;
540
- case "int32": return `get ${name}(): number { return this.reader.getInt32(${field.slotOffset * 4}); }`;
541
- case "int64": return `get ${name}(): bigint { return this.reader.getInt64(${field.slotOffset * 8}); }`;
542
- case "uint8": return `get ${name}(): number { return this.reader.getUint8(${field.slotOffset}); }`;
543
- case "uint16": return `get ${name}(): number { return this.reader.getUint16(${field.slotOffset * 2}); }`;
544
- case "uint32": return `get ${name}(): number { return this.reader.getUint32(${field.slotOffset * 4}); }`;
545
- case "uint64": return `get ${name}(): bigint { return this.reader.getUint64(${field.slotOffset * 8}); }`;
546
- case "float32": return `get ${name}(): number { return this.reader.getFloat32(${field.slotOffset * 4}); }`;
547
- case "float64": return `get ${name}(): number { return this.reader.getFloat64(${field.slotOffset * 8}); }`;
548
- case "text": return `get ${name}(): string { return this.reader.getText(${field.slotOffset}); }`;
549
- case "data": return `get ${name}(): Uint8Array { return this.reader.getData(${field.slotOffset}); }`;
550
- default: return `get ${name}(): unknown { return undefined; }`;
551
- }
552
- }
553
- /**
554
- * 获取字节偏移量
555
- */
556
- function getByteOffset(field, typeKind) {
557
- switch (typeKind) {
558
- case "bool": return field.slotOffset * 8;
559
- case "int8":
560
- case "uint8": return field.slotOffset;
561
- case "int16":
562
- case "uint16":
563
- case "enum": return field.slotOffset * 2;
564
- case "int32":
565
- case "uint32":
566
- case "float32": return field.slotOffset * 4;
567
- case "int64":
568
- case "uint64":
569
- case "float64": return field.slotOffset * 8;
570
- default: return field.slotOffset;
571
- }
572
- }
573
- /**
574
- * 生成字段 setter
575
- */
576
- function generateFieldSetter(field) {
577
- const name = field.name;
578
- const type = field.slotType;
579
- const paramType = getTypeScriptTypeForSetter(type);
580
- const defaultValue = extractDefaultValue(field);
581
- if (!type) return `set${capitalize(name)}(value: unknown): void { /* TODO */ }`;
582
- if (defaultValue !== void 0 && type.kind !== "text" && type.kind !== "data") {
583
- const encodedExpr = generateXorEncode("value", defaultValue, type.kind);
584
- const setterMethod = `set${capitalize(type.kind)}`;
585
- return `set${capitalize(name)}(value: ${paramType}): void { this.builder.${setterMethod}(${getByteOffset(field, type.kind)}, ${encodedExpr}); }`;
586
- }
587
- switch (type.kind) {
588
- case "void": return `set${capitalize(name)}(value: void): void { /* void */ }`;
589
- case "bool": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setBool(${field.slotOffset * 8}, value); }`;
590
- case "int8": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setInt8(${field.slotOffset}, value); }`;
591
- case "int16": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setInt16(${field.slotOffset * 2}, value); }`;
592
- case "int32": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setInt32(${field.slotOffset * 4}, value); }`;
593
- case "int64": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setInt64(${field.slotOffset * 8}, value); }`;
594
- case "uint8": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setUint8(${field.slotOffset}, value); }`;
595
- case "uint16": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setUint16(${field.slotOffset * 2}, value); }`;
596
- case "uint32": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setUint32(${field.slotOffset * 4}, value); }`;
597
- case "uint64": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setUint64(${field.slotOffset * 8}, value); }`;
598
- case "float32": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setFloat32(${field.slotOffset * 4}, value); }`;
599
- case "float64": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setFloat64(${field.slotOffset * 8}, value); }`;
600
- case "text": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setText(${field.slotOffset}, value); }`;
601
- case "data": return `set${capitalize(name)}(value: ${paramType}): void { this.builder.setData(${field.slotOffset}, value); }`;
602
- default: return `set${capitalize(name)}(value: ${paramType}): void { /* TODO */ }`;
603
- }
604
- }
605
- /**
606
- * 获取 TypeScript setter 参数类型
607
- */
608
- function getTypeScriptTypeForSetter(type) {
609
- if (!type) return "unknown";
610
- switch (type.kind) {
611
- case "void": return "void";
612
- case "bool": return "boolean";
613
- case "int8":
614
- case "int16":
615
- case "int32":
616
- case "uint8":
617
- case "uint16":
618
- case "uint32":
619
- case "float32":
620
- case "float64": return "number";
621
- case "int64":
622
- case "uint64": return "bigint";
623
- case "text": return "string";
624
- case "data": return "Uint8Array";
625
- default: return "unknown";
626
- }
627
- }
628
- /**
629
- * 首字母大写
630
- */
631
- function capitalize(str) {
632
- return str.charAt(0).toUpperCase() + str.slice(1);
633
- }
634
- /**
635
- * 生成 Enum 的 TypeScript 代码
636
- */
637
- function generateEnum(node) {
638
- const lines = [];
639
- const enumName = getShortName(node.displayName);
640
- lines.push(`export enum ${enumName} {`);
641
- for (const enumerant of node.enumEnumerants) lines.push(` ${enumerant.name} = ${enumerant.codeOrder},`);
642
- lines.push("}");
643
- return lines.join("\n");
644
- }
645
- /**
646
- * 获取 TypeScript 类型字符串
647
- */
648
- function getTypeScriptType(type, allNodes) {
649
- if (!type) return "unknown";
650
- switch (type.kind) {
651
- case "void": return "void";
652
- case "bool": return "boolean";
653
- case "int8":
654
- case "int16":
655
- case "int32":
656
- case "uint8":
657
- case "uint16":
658
- case "uint32":
659
- case "float32":
660
- case "float64": return "number";
661
- case "int64":
662
- case "uint64": return "bigint";
663
- case "text": return "string";
664
- case "data": return "Uint8Array";
665
- case "list": {
666
- const elementType = type.listElementType;
667
- if (!elementType) return "unknown[]";
668
- return `${getTypeScriptType(elementType, allNodes)}[]`;
669
- }
670
- case "struct": {
671
- const structNode = allNodes.find((n) => n.id === type.typeId);
672
- if (structNode) return getShortName(structNode.displayName);
673
- return "unknown";
674
- }
675
- case "enum": {
676
- const enumNode = allNodes.find((n) => n.id === type.typeId);
677
- if (enumNode) return getShortName(enumNode.displayName);
678
- return "unknown";
679
- }
680
- default: return "unknown";
681
- }
682
- }
683
- /**
684
- * 从 displayName 获取短名称
685
- * 例如 "test-schema.capnp:Person" -> "Person"
686
- * 处理 auto-generated 名称如 "Calculator.evaluate$Params" -> "EvaluateParams"
687
- */
688
- function getShortName(displayName) {
689
- if (!displayName) return "Unknown";
690
- const colonIndex = displayName.lastIndexOf(":");
691
- let name = colonIndex >= 0 ? displayName.substring(colonIndex + 1) : displayName;
692
- if (name.includes(".")) {
693
- const parts = name.split(".");
694
- if (parts.length === 2 && parts[1].includes("$")) {
695
- const methodPart = parts[1];
696
- const dollarIndex = methodPart.indexOf("$");
697
- if (dollarIndex > 0) {
698
- const methodName = methodPart.substring(0, dollarIndex);
699
- const suffix = methodPart.substring(dollarIndex + 1);
700
- name = capitalize(methodName) + suffix;
701
- } else name = capitalize(parts[1]);
702
- } else name = parts[parts.length - 1];
703
- }
704
- name = name.replace(/[^a-zA-Z0-9_]/g, "_");
705
- return name;
706
- }
707
- /**
708
- * 生成 Interface 的 TypeScript 代码
709
- * 包括:Method Constants、Client Class、Server Interface、Server Stub
710
- */
711
- function generateInterface(node, allNodes) {
712
- const lines = [];
713
- const interfaceName = getShortName(node.displayName);
714
- const methods = node.interfaceMethods;
715
- if (methods.length === 0) return `// Interface ${interfaceName} has no methods`;
716
- lines.push(`// ${interfaceName} Method IDs`);
717
- lines.push(`export const ${interfaceName}InterfaceId = ${node.id}n;`);
718
- lines.push(`export const ${interfaceName}MethodIds = {`);
719
- for (const method of methods) lines.push(` ${method.name}: ${method.codeOrder},`);
720
- lines.push("} as const;");
721
- lines.push("");
722
- lines.push(`// ${interfaceName} Server Interface`);
723
- lines.push(`export interface ${interfaceName}Server {`);
724
- for (const method of methods) {
725
- const paramType = getTypeNameById(method.paramStructType, allNodes, "unknown");
726
- const resultType = getTypeNameById(method.resultStructType, allNodes, "unknown");
727
- lines.push(` ${method.name}(context: CallContext<${paramType}Reader, ${resultType}Builder>): Promise<void> | void;`);
728
- }
729
- lines.push("}");
730
- lines.push("");
731
- lines.push(`// ${interfaceName} Server Stub`);
732
- lines.push(`export class ${interfaceName}Stub {`);
733
- lines.push(` private server: ${interfaceName}Server;`);
734
- lines.push("");
735
- lines.push(` constructor(server: ${interfaceName}Server) {`);
736
- lines.push(" this.server = server;");
737
- lines.push(" }");
738
- lines.push("");
739
- lines.push(` static readonly interfaceId = ${node.id}n;`);
740
- lines.push("");
741
- lines.push(" /** Dispatch a method call to the appropriate handler */");
742
- lines.push(" async dispatch(methodId: number, context: CallContext<unknown, unknown>): Promise<void> {");
743
- lines.push(" switch (methodId) {");
744
- for (const method of methods) {
745
- const paramType = getTypeNameById(method.paramStructType, allNodes, "unknown");
746
- const resultType = getTypeNameById(method.resultStructType, allNodes, "unknown");
747
- lines.push(` case ${interfaceName}MethodIds.${method.name}:`);
748
- lines.push(` return this.server.${method.name}(context as CallContext<${paramType}Reader, ${resultType}Builder>);`);
749
- }
750
- lines.push(" default:");
751
- lines.push(" throw new Error(`Unknown method ID: ${methodId}`);");
752
- lines.push(" }");
753
- lines.push(" }");
754
- lines.push("");
755
- lines.push(" /** Check if a method ID is valid */");
756
- lines.push(" isValidMethod(methodId: number): boolean {");
757
- lines.push(" return [");
758
- for (const method of methods) lines.push(` ${interfaceName}MethodIds.${method.name},`);
759
- lines.push(" ].includes(methodId);");
760
- lines.push(" }");
761
- lines.push("}");
762
- lines.push("");
763
- lines.push(`// ${interfaceName} Client Class`);
764
- lines.push(`export class ${interfaceName}Client extends BaseCapabilityClient {`);
765
- lines.push(` static readonly interfaceId = ${node.id}n;`);
766
- lines.push("");
767
- for (const method of methods) {
768
- const paramType = getTypeNameById(method.paramStructType, allNodes, "unknown");
769
- const resultType = getTypeNameById(method.resultStructType, allNodes, "unknown");
770
- lines.push(" /**");
771
- lines.push(` * ${method.name}`);
772
- lines.push(` * @param params - ${paramType}`);
773
- lines.push(` * @returns PipelineClient<${resultType}Reader>`);
774
- lines.push(" */");
775
- lines.push(` ${method.name}(params: ${paramType}Builder): PipelineClient<${resultType}Reader> {`);
776
- lines.push(" return this._call(");
777
- lines.push(` ${interfaceName}Client.interfaceId,`);
778
- lines.push(` ${interfaceName}MethodIds.${method.name},`);
779
- lines.push(" params");
780
- lines.push(` ) as PipelineClient<${resultType}Reader>;`);
781
- lines.push(" }");
782
- lines.push("");
783
- }
784
- lines.push("}");
785
- return lines.join("\n");
786
- }
787
- /**
788
- * 根据类型 ID 获取类型名称
789
- */
790
- function getTypeNameById(id, allNodes, fallback) {
791
- const node = allNodes.find((n) => n.id === id);
792
- if (!node) return fallback;
793
- return getShortName(node.displayName);
794
- }
795
-
796
- //#endregion
797
- //#region src/core/pointer.ts
798
- /**
799
- * Cap'n Proto 指针编解码
800
- * 纯 TypeScript 实现
801
- */
802
- let PointerTag = /* @__PURE__ */ function(PointerTag) {
803
- PointerTag[PointerTag["STRUCT"] = 0] = "STRUCT";
804
- PointerTag[PointerTag["LIST"] = 1] = "LIST";
805
- PointerTag[PointerTag["FAR"] = 2] = "FAR";
806
- PointerTag[PointerTag["OTHER"] = 3] = "OTHER";
807
- return PointerTag;
808
- }({});
809
- let ElementSize = /* @__PURE__ */ function(ElementSize) {
810
- ElementSize[ElementSize["VOID"] = 0] = "VOID";
811
- ElementSize[ElementSize["BIT"] = 1] = "BIT";
812
- ElementSize[ElementSize["BYTE"] = 2] = "BYTE";
813
- ElementSize[ElementSize["TWO_BYTES"] = 3] = "TWO_BYTES";
814
- ElementSize[ElementSize["FOUR_BYTES"] = 4] = "FOUR_BYTES";
815
- ElementSize[ElementSize["EIGHT_BYTES"] = 5] = "EIGHT_BYTES";
816
- ElementSize[ElementSize["POINTER"] = 6] = "POINTER";
817
- ElementSize[ElementSize["COMPOSITE"] = 7] = "COMPOSITE";
818
- ElementSize[ElementSize["INLINE_COMPOSITE"] = 7] = "INLINE_COMPOSITE";
819
- return ElementSize;
820
- }({});
821
- /**
822
- * 解码指针(64位)
823
- */
824
- function decodePointer(ptr) {
825
- const tag = Number(ptr & BigInt(3));
826
- switch (tag) {
827
- case PointerTag.STRUCT: {
828
- const offset = Number(ptr >> BigInt(2)) & 1073741823;
829
- return {
830
- tag,
831
- offset: offset >= 536870912 ? offset - 1073741824 : offset,
832
- dataWords: Number(ptr >> BigInt(32) & BigInt(65535)),
833
- pointerCount: Number(ptr >> BigInt(48) & BigInt(65535))
834
- };
835
- }
836
- case PointerTag.LIST: {
837
- const offset = Number(ptr >> BigInt(2)) & 1073741823;
838
- return {
839
- tag,
840
- offset: offset >= 536870912 ? offset - 1073741824 : offset,
841
- elementSize: Number(ptr >> BigInt(32) & BigInt(7)),
842
- elementCount: Number(ptr >> BigInt(35) & BigInt(536870911))
843
- };
844
- }
845
- case PointerTag.FAR: {
846
- const doubleFar = Boolean(ptr >> BigInt(2) & BigInt(1));
847
- const targetOffset = Number(ptr >> BigInt(3) & BigInt(536870911));
848
- return {
849
- tag,
850
- doubleFar,
851
- targetSegment: Number(ptr >> BigInt(32) & BigInt(4294967295)),
852
- targetOffset
853
- };
854
- }
855
- default: return { tag: PointerTag.OTHER };
856
- }
857
- }
858
-
859
- //#endregion
860
- //#region src/core/segment.ts
861
- /**
862
- * Cap'n Proto Segment 管理
863
- * 纯 TypeScript 实现
864
- */
865
- const WORD_SIZE = 8;
866
- var Segment = class Segment {
867
- buffer;
868
- view;
869
- _size;
870
- constructor(initialCapacity = 1024) {
871
- this.buffer = new ArrayBuffer(initialCapacity);
872
- this.view = new DataView(this.buffer);
873
- this._size = 0;
874
- }
875
- /**
876
- * 从现有 buffer 创建(用于读取)
877
- */
878
- static fromBuffer(buffer) {
879
- const seg = new Segment(0);
880
- seg.buffer = buffer;
881
- seg.view = new DataView(buffer);
882
- seg._size = buffer.byteLength;
883
- return seg;
884
- }
885
- /**
886
- * 确保容量足够
887
- */
888
- ensureCapacity(minBytes) {
889
- if (this.buffer.byteLength >= minBytes) return;
890
- let newCapacity = this.buffer.byteLength * 2;
891
- while (newCapacity < minBytes) newCapacity *= 2;
892
- const newBuffer = new ArrayBuffer(newCapacity);
893
- new Uint8Array(newBuffer).set(new Uint8Array(this.buffer, 0, this._size));
894
- this.buffer = newBuffer;
895
- this.view = new DataView(newBuffer);
896
- }
897
- /**
898
- * 分配空间,返回字偏移
899
- */
900
- allocate(words) {
901
- const bytes = words * WORD_SIZE;
902
- const offset = this._size;
903
- this.ensureCapacity(offset + bytes);
904
- this._size = offset + bytes;
905
- return offset / WORD_SIZE;
906
- }
907
- /**
908
- * 获取字(64位)
909
- */
910
- getWord(wordOffset) {
911
- const byteOffset = wordOffset * WORD_SIZE;
912
- if (byteOffset + 8 > this._size) throw new Error(`Offset ${wordOffset} is outside the bounds of the segment (${this.wordCount} words)`);
913
- const low = BigInt(this.view.getUint32(byteOffset, true));
914
- return BigInt(this.view.getUint32(byteOffset + 4, true)) << BigInt(32) | low;
915
- }
916
- /**
917
- * 设置字(64位)
918
- */
919
- setWord(wordOffset, value) {
920
- const byteOffset = wordOffset * WORD_SIZE;
921
- if (byteOffset + 8 > this.buffer.byteLength) throw new Error(`Offset ${wordOffset} is outside the bounds of the segment`);
922
- this.view.setUint32(byteOffset, Number(value & BigInt(4294967295)), true);
923
- this.view.setUint32(byteOffset + 4, Number(value >> BigInt(32)), true);
924
- }
925
- /**
926
- * 获取原始 buffer(只读到 _size)
927
- */
928
- asUint8Array() {
929
- return new Uint8Array(this.buffer, 0, this._size);
930
- }
931
- /**
932
- * 获取底层 ArrayBuffer
933
- */
934
- getArrayBuffer() {
935
- return this.buffer;
936
- }
937
- /**
938
- * 获取字数量
939
- */
940
- get wordCount() {
941
- return this._size / WORD_SIZE;
942
- }
943
- /**
944
- * 获取字节数量
945
- */
946
- get byteLength() {
947
- return this._size;
948
- }
949
- /**
950
- * 获取 DataView
951
- */
952
- get dataView() {
953
- return this.view;
954
- }
955
- };
956
-
957
- //#endregion
958
- //#region src/core/list.ts
959
- /**
960
- * ListReader - 读取列表
961
- */
962
- var ListReader = class {
963
- segment;
964
- startOffset;
965
- segmentIndex;
966
- constructor(message, segmentIndex, elementSize, elementCount, structSize, wordOffset) {
967
- this.message = message;
968
- this.elementSize = elementSize;
969
- this.elementCount = elementCount;
970
- this.structSize = structSize;
971
- this.segmentIndex = segmentIndex;
972
- this.segment = message.getSegment(segmentIndex);
973
- this.startOffset = wordOffset;
974
- }
975
- /**
976
- * 列表长度
977
- */
978
- get length() {
979
- return this.elementCount;
980
- }
981
- /**
982
- * 获取元素(基础类型)
983
- */
984
- getPrimitive(index) {
985
- if (index < 0 || index >= this.elementCount) throw new RangeError("Index out of bounds");
986
- switch (this.elementSize) {
987
- case ElementSize.BIT: {
988
- const byteOffset = Math.floor(index / 8);
989
- const bitInByte = index % 8;
990
- return (this.segment.dataView.getUint8(this.startOffset * WORD_SIZE + byteOffset) & 1 << bitInByte) !== 0 ? 1 : 0;
991
- }
992
- case ElementSize.BYTE: return this.segment.dataView.getUint8(this.startOffset * WORD_SIZE + index);
993
- case ElementSize.TWO_BYTES: return this.segment.dataView.getUint16(this.startOffset * WORD_SIZE + index * 2, true);
994
- case ElementSize.FOUR_BYTES: return this.segment.dataView.getUint32(this.startOffset * WORD_SIZE + index * 4, true);
995
- case ElementSize.EIGHT_BYTES: {
996
- const offset = this.startOffset * WORD_SIZE + index * 8;
997
- const low = BigInt(this.segment.dataView.getUint32(offset, true));
998
- return BigInt(this.segment.dataView.getUint32(offset + 4, true)) << BigInt(32) | low;
999
- }
1000
- default: throw new Error(`Unsupported element size: ${this.elementSize}`);
1001
- }
1002
- }
1003
- /**
1004
- * 获取结构元素
1005
- */
1006
- getStruct(index) {
1007
- if (!this.structSize) throw new Error("Not a struct list");
1008
- const { dataWords, pointerCount } = this.structSize;
1009
- const size = dataWords + pointerCount;
1010
- const offset = this.startOffset + index * size;
1011
- return new StructReader(this.message, this.segmentIndex, offset, dataWords, pointerCount);
1012
- }
1013
- /**
1014
- * 迭代器
1015
- */
1016
- *[Symbol.iterator]() {
1017
- for (let i = 0; i < this.elementCount; i++) yield this.getPrimitive(i);
1018
- }
1019
- };
1020
-
1021
- //#endregion
1022
- //#region src/core/message-reader.ts
1023
- /**
1024
- * Cap'n Proto MessageReader
1025
- * 纯 TypeScript 实现
1026
- */
1027
- var MessageReader = class {
1028
- segments;
1029
- constructor(buffer) {
1030
- const uint8Array = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer;
1031
- this.segments = [];
1032
- if (uint8Array.byteLength < 8) return;
1033
- const view = new DataView(uint8Array.buffer, uint8Array.byteOffset, uint8Array.byteLength);
1034
- const firstWordLow = view.getUint32(0, true);
1035
- const firstWordHigh = view.getUint32(4, true);
1036
- const segmentCount = (firstWordLow & 4294967295) + 1;
1037
- const firstSegmentSize = firstWordHigh;
1038
- let offset = 8;
1039
- const segmentSizes = [firstSegmentSize];
1040
- for (let i = 1; i < segmentCount; i++) {
1041
- if (offset + 4 > uint8Array.byteLength) {
1042
- this.segments = [];
1043
- return;
1044
- }
1045
- segmentSizes.push(view.getUint32(offset, true));
1046
- offset += 4;
1047
- }
1048
- offset = offset + 7 & -8;
1049
- if (offset > uint8Array.byteLength) {
1050
- this.segments = [];
1051
- return;
1052
- }
1053
- this.segments = [];
1054
- for (const size of segmentSizes) {
1055
- if (offset + size * WORD_SIZE > uint8Array.byteLength) break;
1056
- const segmentBuffer = uint8Array.slice(offset, offset + size * WORD_SIZE);
1057
- this.segments.push(Segment.fromBuffer(segmentBuffer.buffer));
1058
- offset += size * WORD_SIZE;
1059
- }
1060
- }
1061
- /**
1062
- * 获取根结构
1063
- */
1064
- getRoot(_dataWords, _pointerCount) {
1065
- const segment = this.segments[0];
1066
- const ptr = decodePointer(segment.getWord(0));
1067
- if (ptr.tag === PointerTag.STRUCT) {
1068
- const structPtr = ptr;
1069
- const dataOffset = 1 + structPtr.offset;
1070
- return new StructReader(this, 0, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1071
- }
1072
- if (ptr.tag === PointerTag.FAR) {
1073
- const farPtr = ptr;
1074
- const targetSegment = this.getSegment(farPtr.targetSegment);
1075
- if (!targetSegment) throw new Error(`Far pointer references non-existent segment ${farPtr.targetSegment}`);
1076
- if (farPtr.doubleFar) {
1077
- const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1078
- if (landingPadPtr.tag !== PointerTag.FAR) throw new Error("Double-far landing pad is not a far pointer");
1079
- const innerFarPtr = landingPadPtr;
1080
- const finalSegment = this.getSegment(innerFarPtr.targetSegment);
1081
- if (!finalSegment) throw new Error(`Double-far references non-existent segment ${innerFarPtr.targetSegment}`);
1082
- const structPtr = decodePointer(finalSegment.getWord(innerFarPtr.targetOffset));
1083
- const dataOffset = innerFarPtr.targetOffset + 1 + structPtr.offset;
1084
- return new StructReader(this, innerFarPtr.targetSegment, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1085
- }
1086
- const structPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1087
- const dataOffset = farPtr.targetOffset + 1 + structPtr.offset;
1088
- return new StructReader(this, farPtr.targetSegment, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1089
- }
1090
- throw new Error(`Root pointer is not a struct or far pointer: ${ptr.tag}`);
1091
- }
1092
- /**
1093
- * 获取段
1094
- */
1095
- getSegment(index) {
1096
- return this.segments[index];
1097
- }
1098
- /**
1099
- * 解析指针,处理 far pointer 间接寻址
1100
- * 返回 { segmentIndex, wordOffset, pointer },其中 pointer 是实际的 struct/list 指针
1101
- */
1102
- resolvePointer(segmentIndex, wordOffset) {
1103
- const segment = this.getSegment(segmentIndex);
1104
- if (!segment) return null;
1105
- const ptrValue = segment.getWord(wordOffset);
1106
- if (ptrValue === 0n) return null;
1107
- const ptr = decodePointer(ptrValue);
1108
- if (ptr.tag === PointerTag.STRUCT || ptr.tag === PointerTag.LIST) return {
1109
- segmentIndex,
1110
- wordOffset: wordOffset + 1 + ptr.offset,
1111
- pointer: ptr
1112
- };
1113
- if (ptr.tag === PointerTag.FAR) {
1114
- const farPtr = ptr;
1115
- const targetSegment = this.getSegment(farPtr.targetSegment);
1116
- if (!targetSegment) return null;
1117
- if (farPtr.doubleFar) {
1118
- const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1119
- if (landingPadPtr.tag !== PointerTag.FAR) return null;
1120
- const innerFarPtr = landingPadPtr;
1121
- const finalSegment = this.getSegment(innerFarPtr.targetSegment);
1122
- if (!finalSegment) return null;
1123
- const finalPtr = decodePointer(finalSegment.getWord(innerFarPtr.targetOffset));
1124
- if (finalPtr.tag !== PointerTag.STRUCT && finalPtr.tag !== PointerTag.LIST) return null;
1125
- const targetOffset = innerFarPtr.targetOffset + 1 + finalPtr.offset;
1126
- return {
1127
- segmentIndex: innerFarPtr.targetSegment,
1128
- wordOffset: targetOffset,
1129
- pointer: finalPtr
1130
- };
1131
- }
1132
- const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1133
- if (landingPadPtr.tag !== PointerTag.STRUCT && landingPadPtr.tag !== PointerTag.LIST) return null;
1134
- const targetOffset = farPtr.targetOffset + 1 + landingPadPtr.offset;
1135
- return {
1136
- segmentIndex: farPtr.targetSegment,
1137
- wordOffset: targetOffset,
1138
- pointer: landingPadPtr
1139
- };
1140
- }
1141
- return null;
1142
- }
1143
- /**
1144
- * 段数量
1145
- */
1146
- get segmentCount() {
1147
- return this.segments.length;
1148
- }
1149
- };
1150
- /**
1151
- * 结构读取器
1152
- */
1153
- var StructReader = class StructReader {
1154
- constructor(message, segmentIndex, wordOffset, dataWords, pointerCount) {
1155
- this.message = message;
1156
- this.segmentIndex = segmentIndex;
1157
- this.wordOffset = wordOffset;
1158
- this.dataWords = dataWords;
1159
- this.pointerCount = pointerCount;
1160
- }
1161
- /**
1162
- * 获取 bool 字段
1163
- */
1164
- getBool(bitOffset) {
1165
- const byteOffset = Math.floor(bitOffset / 8);
1166
- const bitInByte = bitOffset % 8;
1167
- const segment = this.message.getSegment(this.segmentIndex);
1168
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1169
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1170
- if (dataOffset < 0 || dataOffset >= dataSectionEnd) return false;
1171
- return (segment.dataView.getUint8(dataOffset) & 1 << bitInByte) !== 0;
1172
- }
1173
- /**
1174
- * 获取 int8 字段
1175
- */
1176
- getInt8(byteOffset) {
1177
- const segment = this.message.getSegment(this.segmentIndex);
1178
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1179
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1180
- if (dataOffset < 0 || dataOffset >= dataSectionEnd) return 0;
1181
- return segment.dataView.getInt8(dataOffset);
1182
- }
1183
- /**
1184
- * 获取 int16 字段
1185
- */
1186
- getInt16(byteOffset) {
1187
- const segment = this.message.getSegment(this.segmentIndex);
1188
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1189
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1190
- if (dataOffset < 0 || dataOffset + 2 > dataSectionEnd) return 0;
1191
- return segment.dataView.getInt16(dataOffset, true);
1192
- }
1193
- /**
1194
- * 获取 int32 字段
1195
- */
1196
- getInt32(byteOffset) {
1197
- const segment = this.message.getSegment(this.segmentIndex);
1198
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1199
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1200
- if (dataOffset < 0 || dataOffset + 4 > dataSectionEnd) return 0;
1201
- return segment.dataView.getInt32(dataOffset, true);
1202
- }
1203
- /**
1204
- * 获取 int64 字段
1205
- */
1206
- getInt64(byteOffset) {
1207
- const segment = this.message.getSegment(this.segmentIndex);
1208
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1209
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1210
- if (dataOffset < 0 || dataOffset + 8 > dataSectionEnd) return BigInt(0);
1211
- const low = BigInt(segment.dataView.getUint32(dataOffset, true));
1212
- return BigInt(segment.dataView.getInt32(dataOffset + 4, true)) << BigInt(32) | low;
1213
- }
1214
- /**
1215
- * 获取 uint8 字段
1216
- */
1217
- getUint8(byteOffset) {
1218
- const segment = this.message.getSegment(this.segmentIndex);
1219
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1220
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1221
- if (dataOffset < 0 || dataOffset >= dataSectionEnd) return 0;
1222
- return segment.dataView.getUint8(dataOffset);
1223
- }
1224
- /**
1225
- * 获取 uint16 字段
1226
- */
1227
- getUint16(byteOffset) {
1228
- const segment = this.message.getSegment(this.segmentIndex);
1229
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1230
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1231
- if (dataOffset < 0 || dataOffset + 2 > dataSectionEnd) return 0;
1232
- return segment.dataView.getUint16(dataOffset, true);
1233
- }
1234
- /**
1235
- * 获取 uint32 字段
1236
- */
1237
- getUint32(byteOffset) {
1238
- const segment = this.message.getSegment(this.segmentIndex);
1239
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1240
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1241
- if (dataOffset < 0 || dataOffset + 4 > dataSectionEnd) return 0;
1242
- return segment.dataView.getUint32(dataOffset, true);
1243
- }
1244
- /**
1245
- * 获取 uint64 字段
1246
- */
1247
- getUint64(byteOffset) {
1248
- const segment = this.message.getSegment(this.segmentIndex);
1249
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1250
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1251
- if (dataOffset < 0 || dataOffset + 8 > dataSectionEnd) return BigInt(0);
1252
- const low = BigInt(segment.dataView.getUint32(dataOffset, true));
1253
- return BigInt(segment.dataView.getUint32(dataOffset + 4, true)) << BigInt(32) | low;
1254
- }
1255
- /**
1256
- * 获取 float32 字段
1257
- */
1258
- getFloat32(byteOffset) {
1259
- const segment = this.message.getSegment(this.segmentIndex);
1260
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1261
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1262
- if (dataOffset < 0 || dataOffset + 4 > dataSectionEnd) return 0;
1263
- return segment.dataView.getFloat32(dataOffset, true);
1264
- }
1265
- /**
1266
- * 获取 float64 字段
1267
- */
1268
- getFloat64(byteOffset) {
1269
- const segment = this.message.getSegment(this.segmentIndex);
1270
- const dataOffset = this.wordOffset * WORD_SIZE + byteOffset;
1271
- const dataSectionEnd = this.wordOffset * WORD_SIZE + this.dataWords * WORD_SIZE;
1272
- if (dataOffset < 0 || dataOffset + 8 > dataSectionEnd) return 0;
1273
- return segment.dataView.getFloat64(dataOffset, true);
1274
- }
1275
- /**
1276
- * 获取文本字段
1277
- */
1278
- getText(pointerIndex) {
1279
- const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1280
- const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1281
- if (!resolved) return "";
1282
- const { segmentIndex, wordOffset, pointer } = resolved;
1283
- if (pointer.tag !== PointerTag.LIST) return "";
1284
- const listPtr = pointer;
1285
- const segment = this.message.getSegment(segmentIndex);
1286
- const byteLength = listPtr.elementCount > 0 ? listPtr.elementCount - 1 : 0;
1287
- if (byteLength === 0) return "";
1288
- const bytes = new Uint8Array(segment.dataView.buffer, wordOffset * WORD_SIZE, byteLength);
1289
- return new TextDecoder().decode(bytes);
1290
- }
1291
- /**
1292
- * 获取数据字段
1293
- * Data is stored as List(UInt8) without NUL terminator
1294
- * @param pointerIndex - The index of the pointer in the pointer section
1295
- * @returns Uint8Array of the data content, or undefined if null pointer
1296
- */
1297
- getData(pointerIndex) {
1298
- const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1299
- const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1300
- if (!resolved) return void 0;
1301
- const { segmentIndex, wordOffset, pointer } = resolved;
1302
- if (pointer.tag !== PointerTag.LIST) return void 0;
1303
- const listPtr = pointer;
1304
- const segment = this.message.getSegment(segmentIndex);
1305
- const byteLength = listPtr.elementCount;
1306
- if (byteLength === 0) return new Uint8Array(0);
1307
- const bytes = new Uint8Array(segment.dataView.buffer, wordOffset * WORD_SIZE, byteLength);
1308
- return new Uint8Array(bytes);
1309
- }
1310
- /**
1311
- * 获取嵌套结构
1312
- */
1313
- getStruct(pointerIndex, _dataWords, _pointerCount) {
1314
- const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1315
- const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1316
- if (!resolved) return void 0;
1317
- const { segmentIndex, wordOffset, pointer } = resolved;
1318
- if (pointer.tag !== PointerTag.STRUCT) return void 0;
1319
- const structPtr = pointer;
1320
- return new StructReader(this.message, segmentIndex, wordOffset, structPtr.dataWords, structPtr.pointerCount);
1321
- }
1322
- /**
1323
- * 获取列表
1324
- */
1325
- getList(pointerIndex, _elementSize, structSize) {
1326
- const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1327
- const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1328
- if (!resolved) return void 0;
1329
- const { segmentIndex, wordOffset, pointer } = resolved;
1330
- if (pointer.tag !== PointerTag.LIST) return void 0;
1331
- const listPtr = pointer;
1332
- let targetOffset = wordOffset;
1333
- let elementCount = listPtr.elementCount;
1334
- let actualStructSize = structSize;
1335
- const segment = this.message.getSegment(segmentIndex);
1336
- if (listPtr.elementSize === ElementSize.COMPOSITE) {
1337
- if (targetOffset < 0 || targetOffset >= segment.wordCount) return;
1338
- try {
1339
- const tagWord = segment.getWord(targetOffset);
1340
- elementCount = Number(tagWord & BigInt(4294967295));
1341
- actualStructSize = {
1342
- dataWords: Number(tagWord >> BigInt(32) & BigInt(65535)),
1343
- pointerCount: Number(tagWord >> BigInt(48) & BigInt(65535))
1344
- };
1345
- targetOffset += 1;
1346
- } catch {
1347
- return;
1348
- }
1349
- }
1350
- return new ListReader(this.message, segmentIndex, listPtr.elementSize, elementCount, actualStructSize, targetOffset);
1351
- }
1352
- };
1353
-
1354
- //#endregion
1355
- //#region src/schema/schema-reader.ts
1356
- /**
1357
- * Cap'n Proto 编译后 Schema 的 TypeScript Reader
1358
- * 基于官方 schema.capnp 手动编写
7
+ * Cap'n Proto Unified CLI
1359
8
  *
1360
- * 这是自举的基础:我们需要先能读取 schema 才能生成 schema 的代码
9
+ * Usage: capnp <command> [options]
1361
10
  *
1362
- * 结构信息来自: capnp compile -ocapnp schema.capnp
1363
- */
1364
- var NodeReader = class {
1365
- constructor(reader) {
1366
- this.reader = reader;
1367
- }
1368
- get id() {
1369
- return this.reader.getUint64(0);
1370
- }
1371
- get displayName() {
1372
- return this.reader.getText(0);
1373
- }
1374
- get displayNamePrefixLength() {
1375
- return this.reader.getUint32(8);
1376
- }
1377
- get scopeId() {
1378
- return this.reader.getUint64(16);
1379
- }
1380
- /** union tag 在 bits [96, 112) = bytes [12, 14) */
1381
- get unionTag() {
1382
- return this.reader.getUint16(12);
1383
- }
1384
- get isFile() {
1385
- return this.unionTag === 0;
1386
- }
1387
- get isStruct() {
1388
- return this.unionTag === 1;
1389
- }
1390
- get isEnum() {
1391
- return this.unionTag === 2;
1392
- }
1393
- get isInterface() {
1394
- return this.unionTag === 3;
1395
- }
1396
- get isConst() {
1397
- return this.unionTag === 4;
1398
- }
1399
- get isAnnotation() {
1400
- return this.unionTag === 5;
1401
- }
1402
- get structDataWordCount() {
1403
- return this.reader.getUint16(14);
1404
- }
1405
- get structPointerCount() {
1406
- return this.reader.getUint16(24);
1407
- }
1408
- get structPreferredListEncoding() {
1409
- return this.reader.getUint16(26);
1410
- }
1411
- get structIsGroup() {
1412
- return this.reader.getBool(224);
1413
- }
1414
- get structDiscriminantCount() {
1415
- return this.reader.getUint16(30);
1416
- }
1417
- get structDiscriminantOffset() {
1418
- return this.reader.getUint32(32);
1419
- }
1420
- get structFields() {
1421
- const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1422
- dataWords: 3,
1423
- pointerCount: 4
1424
- });
1425
- if (!listReader) return [];
1426
- const fields = [];
1427
- for (let i = 0; i < listReader.length; i++) {
1428
- const field = new FieldReader(listReader.getStruct(i));
1429
- if (!field.name && i > 0) break;
1430
- fields.push(field);
1431
- }
1432
- return fields;
1433
- }
1434
- get enumEnumerants() {
1435
- const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1436
- dataWords: 1,
1437
- pointerCount: 2
1438
- });
1439
- if (!listReader) return [];
1440
- const enumerants = [];
1441
- for (let i = 0; i < Math.min(listReader.length, 10); i++) try {
1442
- const enumerant = new EnumerantReader(listReader.getStruct(i));
1443
- if (!enumerant.name) break;
1444
- enumerants.push(enumerant);
1445
- } catch (_e) {
1446
- break;
1447
- }
1448
- return enumerants;
1449
- }
1450
- get interfaceMethods() {
1451
- const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1452
- dataWords: 5,
1453
- pointerCount: 2
1454
- });
1455
- if (!listReader) return [];
1456
- const methods = [];
1457
- for (let i = 0; i < listReader.length; i++) try {
1458
- const method = new MethodReader(listReader.getStruct(i));
1459
- if (!method.name && i > 0) break;
1460
- methods.push(method);
1461
- } catch (_e) {
1462
- break;
1463
- }
1464
- return methods;
1465
- }
1466
- get nestedNodes() {
1467
- const listReader = this.reader.getList(1, ElementSize.INLINE_COMPOSITE, {
1468
- dataWords: 1,
1469
- pointerCount: 1
1470
- });
1471
- if (!listReader) return [];
1472
- const nodes = [];
1473
- for (let i = 0; i < listReader.length; i++) {
1474
- const itemReader = listReader.getStruct(i);
1475
- nodes.push(new NestedNodeReader(itemReader));
1476
- }
1477
- return nodes;
1478
- }
1479
- };
1480
- var FieldReader = class {
1481
- constructor(reader) {
1482
- this.reader = reader;
1483
- }
1484
- get name() {
1485
- return this.reader.getText(0);
1486
- }
1487
- get codeOrder() {
1488
- return this.reader.getUint16(0);
1489
- }
1490
- get discriminantValue() {
1491
- return this.reader.getUint16(2);
1492
- }
1493
- /** union tag 在 bits [64, 80) = bytes [8, 10) */
1494
- get unionTag() {
1495
- return this.reader.getUint16(8);
1496
- }
1497
- get isSlot() {
1498
- return this.unionTag === 0;
1499
- }
1500
- get isGroup() {
1501
- return this.unionTag === 1;
1502
- }
1503
- get slotOffset() {
1504
- return this.reader.getUint32(4);
1505
- }
1506
- get slotType() {
1507
- const typeReader = this.reader.getStruct(2, 3, 1);
1508
- return typeReader ? new TypeReader(typeReader) : null;
1509
- }
1510
- get groupTypeId() {
1511
- return this.reader.getUint64(16);
1512
- }
1513
- get defaultValue() {
1514
- const valueReader = this.reader.getStruct(3, 2, 1);
1515
- return valueReader ? new ValueReader(valueReader) : null;
1516
- }
1517
- };
1518
- var TypeReader = class TypeReader {
1519
- constructor(reader) {
1520
- this.reader = reader;
1521
- }
1522
- get kind() {
1523
- return TYPE_KIND_MAP[this.reader.getUint16(0)] ?? "unknown";
1524
- }
1525
- get isPrimitive() {
1526
- const k = this.kind;
1527
- return k !== "list" && k !== "enum" && k !== "struct" && k !== "interface" && k !== "anyPointer";
1528
- }
1529
- get listElementType() {
1530
- if (this.kind !== "list") return null;
1531
- const elementReader = this.reader.getStruct(0, 3, 1);
1532
- return elementReader ? new TypeReader(elementReader) : null;
1533
- }
1534
- get typeId() {
1535
- const k = this.kind;
1536
- if (k === "enum" || k === "struct" || k === "interface") return this.reader.getUint64(8);
1537
- return null;
1538
- }
1539
- };
1540
- const TYPE_KIND_MAP = {
1541
- 0: "void",
1542
- 1: "bool",
1543
- 2: "int8",
1544
- 3: "int16",
1545
- 4: "int32",
1546
- 5: "int64",
1547
- 6: "uint8",
1548
- 7: "uint16",
1549
- 8: "uint32",
1550
- 9: "uint64",
1551
- 10: "float32",
1552
- 11: "float64",
1553
- 12: "text",
1554
- 13: "data",
1555
- 14: "list",
1556
- 15: "enum",
1557
- 16: "struct",
1558
- 17: "interface",
1559
- 18: "anyPointer"
1560
- };
1561
- var ValueReader = class {
1562
- constructor(reader) {
1563
- this.reader = reader;
1564
- }
1565
- /** union tag 在 bits [0, 16) = bytes [0, 2) */
1566
- get unionTag() {
1567
- return this.reader.getUint16(0);
1568
- }
1569
- get isVoid() {
1570
- return this.unionTag === 0;
1571
- }
1572
- get isBool() {
1573
- return this.unionTag === 1;
1574
- }
1575
- get isInt8() {
1576
- return this.unionTag === 2;
1577
- }
1578
- get isInt16() {
1579
- return this.unionTag === 3;
1580
- }
1581
- get isInt32() {
1582
- return this.unionTag === 4;
1583
- }
1584
- get isInt64() {
1585
- return this.unionTag === 5;
1586
- }
1587
- get isUint8() {
1588
- return this.unionTag === 6;
1589
- }
1590
- get isUint16() {
1591
- return this.unionTag === 7;
1592
- }
1593
- get isUint32() {
1594
- return this.unionTag === 8;
1595
- }
1596
- get isUint64() {
1597
- return this.unionTag === 9;
1598
- }
1599
- get isFloat32() {
1600
- return this.unionTag === 10;
1601
- }
1602
- get isFloat64() {
1603
- return this.unionTag === 11;
1604
- }
1605
- get isText() {
1606
- return this.unionTag === 12;
1607
- }
1608
- get isData() {
1609
- return this.unionTag === 13;
1610
- }
1611
- get isList() {
1612
- return this.unionTag === 14;
1613
- }
1614
- get isEnum() {
1615
- return this.unionTag === 15;
1616
- }
1617
- get isStruct() {
1618
- return this.unionTag === 16;
1619
- }
1620
- get isInterface() {
1621
- return this.unionTag === 17;
1622
- }
1623
- get isAnyPointer() {
1624
- return this.unionTag === 18;
1625
- }
1626
- get boolValue() {
1627
- return this.reader.getBool(16);
1628
- }
1629
- get int8Value() {
1630
- return this.reader.getInt8(2);
1631
- }
1632
- get int16Value() {
1633
- return this.reader.getInt16(2);
1634
- }
1635
- get int32Value() {
1636
- return this.reader.getInt32(4);
1637
- }
1638
- get int64Value() {
1639
- return this.reader.getInt64(8);
1640
- }
1641
- get uint8Value() {
1642
- return this.reader.getUint8(2);
1643
- }
1644
- get uint16Value() {
1645
- return this.reader.getUint16(2);
1646
- }
1647
- get uint32Value() {
1648
- return this.reader.getUint32(4);
1649
- }
1650
- get uint64Value() {
1651
- return this.reader.getUint64(8);
1652
- }
1653
- get float32Value() {
1654
- return this.reader.getFloat32(4);
1655
- }
1656
- get float64Value() {
1657
- return this.reader.getFloat64(8);
1658
- }
1659
- get enumValue() {
1660
- return this.reader.getUint16(2);
1661
- }
1662
- getAsNumber() {
1663
- if (this.isInt8) return this.int8Value;
1664
- if (this.isInt16) return this.int16Value;
1665
- if (this.isInt32) return this.int32Value;
1666
- if (this.isUint8) return this.uint8Value;
1667
- if (this.isUint16) return this.uint16Value;
1668
- if (this.isUint32) return this.uint32Value;
1669
- if (this.isFloat32) return this.float32Value;
1670
- if (this.isFloat64) return this.float64Value;
1671
- if (this.isEnum) return this.enumValue;
1672
- }
1673
- getAsBigint() {
1674
- if (this.isInt64) return this.int64Value;
1675
- if (this.isUint64) return this.uint64Value;
1676
- }
1677
- getAsBoolean() {
1678
- if (this.isBool) return this.boolValue;
1679
- }
1680
- };
1681
- var MethodReader = class {
1682
- constructor(reader) {
1683
- this.reader = reader;
1684
- }
1685
- get name() {
1686
- return this.reader.getText(0);
1687
- }
1688
- get codeOrder() {
1689
- return this.reader.getUint16(0);
1690
- }
1691
- get paramStructType() {
1692
- return this.reader.getUint64(8);
1693
- }
1694
- get resultStructType() {
1695
- return this.reader.getUint64(16);
1696
- }
1697
- };
1698
- var EnumerantReader = class {
1699
- constructor(reader) {
1700
- this.reader = reader;
1701
- }
1702
- get name() {
1703
- return this.reader.getText(0);
1704
- }
1705
- get codeOrder() {
1706
- return this.reader.getUint16(0);
1707
- }
1708
- };
1709
- var NestedNodeReader = class {
1710
- constructor(reader) {
1711
- this.reader = reader;
1712
- }
1713
- get name() {
1714
- return this.reader.getText(0);
1715
- }
1716
- get id() {
1717
- return this.reader.getUint64(0);
1718
- }
1719
- };
1720
- var CodeGeneratorRequestReader = class CodeGeneratorRequestReader {
1721
- constructor(message) {
1722
- this.message = message;
1723
- }
1724
- static fromBuffer(buffer) {
1725
- return new CodeGeneratorRequestReader(new MessageReader(buffer));
1726
- }
1727
- get nodes() {
1728
- const listReader = this.message.getRoot(0, 4).getList(0, ElementSize.INLINE_COMPOSITE, {
1729
- dataWords: 6,
1730
- pointerCount: 6
1731
- });
1732
- if (!listReader) return [];
1733
- const nodes = [];
1734
- for (let i = 0; i < listReader.length; i++) {
1735
- const nodeReader = listReader.getStruct(i);
1736
- nodes.push(new NodeReader(nodeReader));
1737
- }
1738
- return nodes;
1739
- }
1740
- get requestedFiles() {
1741
- const listReader = this.message.getRoot(0, 4).getList(1, ElementSize.INLINE_COMPOSITE, {
1742
- dataWords: 1,
1743
- pointerCount: 2
1744
- });
1745
- if (!listReader) return [];
1746
- const files = [];
1747
- for (let i = 0; i < listReader.length; i++) try {
1748
- const file = new RequestedFileReader(listReader.getStruct(i));
1749
- if (!file.filename && files.length > 0) break;
1750
- files.push(file);
1751
- } catch (_e) {
1752
- break;
1753
- }
1754
- return files;
1755
- }
1756
- };
1757
- var RequestedFileReader = class {
1758
- constructor(reader) {
1759
- this.reader = reader;
1760
- }
1761
- get id() {
1762
- return this.reader.getUint64(0);
1763
- }
1764
- get filename() {
1765
- return this.reader.getText(0);
1766
- }
1767
- };
1768
-
1769
- //#endregion
1770
- //#region src/cli.ts
1771
- /**
1772
- * Cap'n Proto CLI
1773
- *
1774
- * Usage:
1775
- * capnp gen schema.capnp -o types.ts
11
+ * Commands:
12
+ * gen Generate TypeScript code from schema
13
+ * json Convert between Cap'n Proto and JSON
14
+ * compat Check schema compatibility
15
+ * audit Security audit message files
16
+ * help Show help for a command
1776
17
  */
1777
18
  const { values, positionals } = parseArgs({
1778
19
  args: process.argv.slice(2),
1779
20
  options: {
1780
- output: {
1781
- type: "string",
1782
- short: "o"
1783
- },
1784
- outDir: {
1785
- type: "string",
1786
- short: "d"
1787
- },
1788
- runtimePath: {
1789
- type: "string",
1790
- short: "r"
1791
- },
1792
- dynamic: {
1793
- type: "boolean",
1794
- short: "D"
1795
- },
1796
- interactive: {
1797
- type: "boolean",
1798
- short: "i"
1799
- },
1800
21
  help: {
1801
22
  type: "boolean",
1802
23
  short: "h"
@@ -1806,489 +27,99 @@ const { values, positionals } = parseArgs({
1806
27
  short: "v"
1807
28
  }
1808
29
  },
1809
- allowPositionals: true
30
+ allowPositionals: true,
31
+ strict: false
1810
32
  });
1811
- const VERSION = "3.0.0";
1812
- if (values.version) {
1813
- console.log(VERSION);
1814
- process.exit(0);
1815
- }
1816
- if (values.help || positionals.length === 0) {
33
+ const VERSION = "0.9.1";
34
+ function printMainUsage() {
1817
35
  console.log(`
1818
- Cap'n Proto TypeScript Code Generator v3
36
+ Cap'n Proto TypeScript CLI v${VERSION}
37
+
38
+ Usage: capnp <command> [options]
1819
39
 
1820
- Usage: capnp-ts-codegen <schema.capnp> [options]
40
+ Commands:
41
+ gen Generate TypeScript code from .capnp schema
42
+ json Convert between Cap'n Proto binary and JSON
43
+ compat Check schema compatibility between versions
44
+ audit Security audit message files
45
+ bench Run performance benchmarks
1821
46
 
1822
47
  Options:
1823
- -o, --output Output file (default: stdout for single file)
1824
- -d, --outDir Output directory for multiple files
1825
- -r, --runtimePath Runtime library import path (default: @naeemo/capnp)
1826
- -D, --dynamic Generate dynamic schema loading code
1827
- -i, --interactive Start interactive schema query tool
1828
- -h, --help Show this help
1829
- -v, --version Show version
48
+ -h, --help Show this help
49
+ -v, --version Show version
1830
50
 
1831
51
  Examples:
1832
- capnp-ts-codegen schema.capnp -o schema.ts
1833
- capnp-ts-codegen schema.capnp -d ./generated
1834
- capnp-ts-codegen schema.capnp -o schema.ts -r ../runtime
1835
- capnp-ts-codegen schema.capnp -D -o schema-dynamic.ts
1836
- capnp-ts-codegen schema.capnp -i
1837
-
1838
- Features:
1839
- - Struct with all primitive types
1840
- - Enum
1841
- - List<T>
1842
- - Text, Data
1843
- - Nested struct references
1844
- - Union (discriminant handling)
1845
- - Group
1846
- - Default values (XOR encoding)
1847
- - Multi-segment messages
1848
- - Interface (RPC client/server generation)
1849
- - Dynamic schema loading (Phase 7)
52
+ capnp gen schema.capnp -o types.ts
53
+ capnp json to-json -i data.bin -s schema.json
54
+ capnp compat old.json new.json
55
+ capnp audit message.bin
56
+ capnp bench --sizes 1KB,10KB,100KB --vs-json
1850
57
 
1851
- Not yet supported:
1852
- - Const
1853
- - Advanced RPC features (Level 2-4)
58
+ Run 'capnp <command> --help' for more information on a command.
1854
59
  `);
1855
- process.exit(0);
1856
- }
1857
- const inputFile = positionals[0];
1858
- if (!existsSync(inputFile)) {
1859
- console.error(`Error: File not found: ${inputFile}`);
1860
- process.exit(1);
1861
- }
1862
- function checkCapnpTool() {
1863
- try {
1864
- execSync("capnp --version", { stdio: "ignore" });
1865
- return true;
1866
- } catch {
1867
- return false;
1868
- }
1869
60
  }
1870
61
  async function main() {
1871
- if (values.interactive) {
1872
- await runInteractiveMode(inputFile);
1873
- return;
1874
- }
1875
- if (!checkCapnpTool()) {
1876
- console.error("Error: capnp tool not found. Please install Cap'n Proto.");
1877
- console.error(" macOS: brew install capnp");
1878
- console.error(" Ubuntu/Debian: apt-get install capnproto");
1879
- console.error(" Other: https://capnproto.org/install.html");
1880
- process.exit(1);
1881
- }
1882
- const tmpDir = mkdtempSync(join(tmpdir(), "capnp-ts-"));
1883
- const binFile = join(tmpDir, "schema.bin");
1884
- try {
1885
- console.error(`Compiling ${inputFile}...`);
1886
- const inputDir = dirname(inputFile);
1887
- execSync(`capnp compile -o- "${inputFile}" > "${binFile}"`, {
1888
- cwd: inputDir,
1889
- stdio: [
1890
- "ignore",
1891
- "ignore",
1892
- "pipe"
1893
- ]
1894
- });
1895
- console.error("Reading binary schema...");
1896
- const buffer = readFileSync(binFile);
1897
- const arrayBuffer = new Uint8Array(buffer.byteLength);
1898
- arrayBuffer.set(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength));
1899
- if (values.dynamic) {
1900
- console.error("Generating dynamic schema loading code...");
1901
- const dynamicCode = generateDynamicLoadingCode(inputFile, arrayBuffer.buffer);
1902
- if (values.output) {
1903
- writeFileSync(values.output, dynamicCode);
1904
- console.error(`Dynamic loading code written to ${values.output}`);
1905
- } else console.log(dynamicCode);
1906
- return;
1907
- }
1908
- console.error("Generating TypeScript code...");
1909
- const files = generateFromRequest(CodeGeneratorRequestReader.fromBuffer(arrayBuffer.buffer), { runtimeImportPath: values.runtimePath || "@naeemo/capnp" });
1910
- if (values.outDir) {
1911
- mkdirSync(values.outDir, { recursive: true });
1912
- for (const [filename, code] of files) {
1913
- const outPath = join(values.outDir, filename);
1914
- mkdirSync(dirname(outPath), { recursive: true });
1915
- writeFileSync(outPath, code);
1916
- console.error(`Generated: ${outPath}`);
1917
- }
1918
- } else if (values.output) {
1919
- const firstFile = files.values().next().value;
1920
- if (firstFile) {
1921
- writeFileSync(values.output, firstFile);
1922
- console.error(`Output written to ${values.output}`);
1923
- } else {
1924
- console.error("Error: No files generated");
1925
- process.exit(1);
1926
- }
1927
- } else {
1928
- const firstFile = files.values().next().value;
1929
- if (firstFile) console.log(firstFile);
1930
- else {
1931
- console.error("Error: No files generated");
1932
- process.exit(1);
1933
- }
1934
- }
1935
- } catch (err) {
1936
- console.error("Error:", err.message);
1937
- if (err.stderr) console.error(err.stderr.toString());
1938
- process.exit(1);
1939
- } finally {
1940
- rmSync(tmpDir, {
1941
- recursive: true,
1942
- force: true
1943
- });
1944
- }
1945
- }
1946
- main();
1947
- /**
1948
- * Generate dynamic schema loading code for the given schema file
1949
- */
1950
- function generateDynamicLoadingCode(inputFile, buffer) {
1951
- const nodes = CodeGeneratorRequestReader.fromBuffer(buffer).nodes;
1952
- const runtimePath = values.runtimePath || "@naeemo/capnp";
1953
- const schemaName = basename(inputFile, ".capnp");
1954
- const structTypes = [];
1955
- const interfaceTypes = [];
1956
- for (const node of nodes) {
1957
- const id = node.id;
1958
- const displayName = node.displayName;
1959
- const shortName = displayName.split(".").pop() || displayName;
1960
- if (node.isStruct) structTypes.push({
1961
- id: `0x${id.toString(16)}n`,
1962
- name: shortName,
1963
- displayName
1964
- });
1965
- else if (node.isInterface) interfaceTypes.push({
1966
- id: `0x${id.toString(16)}n`,
1967
- name: shortName,
1968
- displayName
1969
- });
1970
- }
1971
- return `/**
1972
- * Dynamic Schema Loading for ${schemaName}.capnp
1973
- *
1974
- * This file provides runtime schema loading capabilities for ${schemaName}.capnp
1975
- * Generated by capnp-ts-codegen --dynamic
1976
- *
1977
- * Usage:
1978
- * import { load${toPascalCase(schemaName)}Schema, ${structTypes.map((t) => t.name).join(", ")} } from './${schemaName}-dynamic';
1979
- *
1980
- * // Load schema from remote connection
1981
- * const schema = await load${toPascalCase(schemaName)}Schema(connection);
1982
- *
1983
- * // Use dynamic reader
1984
- * const reader = createDynamicReader(schema.Person, buffer);
1985
- * console.log(reader.get('name'));
1986
- */
1987
-
1988
- import {
1989
- RpcConnection,
1990
- createDynamicReader,
1991
- createDynamicWriter,
1992
- dumpDynamicReader,
1993
- type SchemaNode,
1994
- type SchemaRegistry,
1995
- } from '${runtimePath}';
1996
-
1997
- // =============================================================================
1998
- // Type IDs
1999
- // =============================================================================
2000
-
2001
- ${structTypes.map((t) => `/** Type ID for ${t.displayName} */\nexport const ${t.name}TypeId = ${t.id};`).join("\n")}
2002
-
2003
- ${interfaceTypes.map((t) => `/** Interface ID for ${t.displayName} */\nexport const ${t.name}InterfaceId = ${t.id};`).join("\n")}
2004
-
2005
- // =============================================================================
2006
- // Schema Cache
2007
- // =============================================================================
2008
-
2009
- let cachedSchemaRegistry: SchemaRegistry | null = null;
2010
-
2011
- // =============================================================================
2012
- // Schema Loading Functions
2013
- // =============================================================================
2014
-
2015
- /**
2016
- * Load all schemas for ${schemaName}.capnp from a remote connection.
2017
- * This fetches schema information dynamically and caches it for reuse.
2018
- *
2019
- * @param connection - The RPC connection to fetch schemas from
2020
- * @returns A registry containing all loaded schemas
2021
- */
2022
- export async function load${toPascalCase(schemaName)}Schema(connection: RpcConnection): Promise<SchemaRegistry> {
2023
- if (cachedSchemaRegistry) {
2024
- return cachedSchemaRegistry;
2025
- }
2026
-
2027
- // Fetch all schemas
2028
- const typeIds = [
2029
- ${structTypes.map((t) => `${t.name}TypeId`).join(",\n ")}
2030
- ];
2031
-
2032
- for (const typeId of typeIds) {
2033
- try {
2034
- await connection.getDynamicSchema(typeId);
2035
- } catch (err) {
2036
- console.warn(\`Failed to load schema for type \${typeId}:\`, err);
2037
- }
2038
- }
2039
-
2040
- cachedSchemaRegistry = connection.getSchemaRegistry();
2041
- return cachedSchemaRegistry;
2042
- }
2043
-
2044
- /**
2045
- * Get a specific schema node by type ID.
2046
- * Loads from remote if not already cached.
2047
- *
2048
- * @param connection - The RPC connection
2049
- * @param typeId - The type ID to fetch
2050
- * @returns The schema node
2051
- */
2052
- export async function getSchema(connection: RpcConnection, typeId: bigint): Promise<SchemaNode> {
2053
- return connection.getDynamicSchema(typeId);
2054
- }
2055
-
2056
- /**
2057
- * Clear the schema cache.
2058
- * Call this if you need to re-fetch schemas from the remote server.
2059
- */
2060
- export function clearSchemaCache(): void {
2061
- cachedSchemaRegistry = null;
2062
- }
2063
-
2064
- // =============================================================================
2065
- // Dynamic Reader Helpers
2066
- // =============================================================================
2067
-
2068
- ${structTypes.map((t) => `
2069
- /**
2070
- * Create a dynamic reader for ${t.name}
2071
- *
2072
- * @param buffer - The Cap'n Proto message buffer
2073
- * @param registry - Optional schema registry (will use cached if available)
2074
- * @returns A DynamicReader for the message
2075
- */
2076
- export function create${toPascalCase(t.name)}Reader(
2077
- buffer: ArrayBuffer | Uint8Array,
2078
- registry?: SchemaRegistry
2079
- ): DynamicReader {
2080
- const reg = registry || cachedSchemaRegistry;
2081
- if (!reg) {
2082
- throw new Error('Schema registry not loaded. Call load${toPascalCase(schemaName)}Schema first.');
2083
- }
2084
-
2085
- const schema = reg.getNode(${t.name}TypeId);
2086
- if (!schema) {
2087
- throw new Error('Schema for ${t.name} not found in registry');
2088
- }
2089
-
2090
- return createDynamicReader(schema, buffer);
2091
- }
2092
- `).join("\n")}
2093
-
2094
- // =============================================================================
2095
- // Utility Functions
2096
- // =============================================================================
2097
-
2098
- /**
2099
- * Dump all fields from a dynamic reader for debugging
2100
- */
2101
- export { dumpDynamicReader };
2102
-
2103
- /**
2104
- * List all available types in this schema
2105
- */
2106
- export function listTypes(): Array<{ name: string; typeId: string; kind: 'struct' | 'interface' }> {
2107
- return [
2108
- ${structTypes.map((t) => `{ name: '${t.name}', typeId: '${t.id}', kind: 'struct' as const }`).join(",\n ")},
2109
- ${interfaceTypes.map((t) => `{ name: '${t.name}', typeId: '${t.id}', kind: 'interface' as const }`).join(",\n ")},
2110
- ];
2111
- }
2112
- `;
2113
- }
2114
- /**
2115
- * Run interactive schema query tool
2116
- */
2117
- async function runInteractiveMode(inputFile) {
2118
- if (!checkCapnpTool()) {
2119
- console.error("Error: capnp tool not found. Please install Cap'n Proto.");
2120
- process.exit(1);
2121
- }
2122
- const tmpDir = mkdtempSync(join(tmpdir(), "capnp-ts-"));
2123
- const binFile = join(tmpDir, "schema.bin");
2124
- try {
2125
- console.log(`\n🔍 Loading schema: ${inputFile}...\n`);
2126
- const inputDir = dirname(inputFile);
2127
- execSync(`capnp compile -o- "${inputFile}" > "${binFile}"`, {
2128
- cwd: inputDir,
2129
- stdio: [
2130
- "ignore",
2131
- "ignore",
2132
- "pipe"
2133
- ]
2134
- });
2135
- const buffer = readFileSync(binFile);
2136
- const arrayBuffer = new Uint8Array(buffer.byteLength);
2137
- arrayBuffer.set(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength));
2138
- const nodes = CodeGeneratorRequestReader.fromBuffer(arrayBuffer.buffer).nodes;
2139
- const typeIndex = /* @__PURE__ */ new Map();
2140
- for (const node of nodes) {
2141
- const id = node.id;
2142
- const displayName = node.displayName;
2143
- const shortName = displayName.split(".").pop() || displayName;
2144
- let kind = "unknown";
2145
- if (node.isStruct) kind = "struct";
2146
- else if (node.isInterface) kind = "interface";
2147
- else if (node.isEnum) kind = "enum";
2148
- else if (node.isConst) kind = "const";
2149
- typeIndex.set(shortName, {
2150
- id,
2151
- displayName,
2152
- kind,
2153
- node
2154
- });
2155
- typeIndex.set(displayName, {
2156
- id,
2157
- displayName,
2158
- kind,
2159
- node
2160
- });
2161
- typeIndex.set(id.toString(16), {
2162
- id,
2163
- displayName,
2164
- kind,
2165
- node
2166
- });
2167
- }
2168
- console.log("📋 Available types:");
2169
- console.log("─".repeat(60));
2170
- const structs = [];
2171
- const interfaces = [];
2172
- const enums = [];
2173
- for (const [name, info] of typeIndex) {
2174
- if (name.includes(".")) continue;
2175
- if (info.kind === "struct") structs.push(name);
2176
- else if (info.kind === "interface") interfaces.push(name);
2177
- else if (info.kind === "enum") enums.push(name);
2178
- }
2179
- if (structs.length > 0) {
2180
- console.log("\n🏗️ Structs:");
2181
- for (const name of structs.sort()) {
2182
- const info = typeIndex.get(name);
2183
- console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2184
- }
2185
- }
2186
- if (interfaces.length > 0) {
2187
- console.log("\n🔌 Interfaces:");
2188
- for (const name of interfaces.sort()) {
2189
- const info = typeIndex.get(name);
2190
- console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2191
- }
2192
- }
2193
- if (enums.length > 0) {
2194
- console.log("\n📊 Enums:");
2195
- for (const name of enums.sort()) {
2196
- const info = typeIndex.get(name);
2197
- console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2198
- }
2199
- }
2200
- console.log(`\n${"─".repeat(60)}`);
2201
- console.log("💡 Commands:");
2202
- console.log(" inspect <type> - Show detailed information about a type");
2203
- console.log(" ids - List all type IDs");
2204
- console.log(" export - Export schema info as JSON");
2205
- console.log(" quit - Exit interactive mode");
2206
- console.log("");
2207
- const stdin = process.stdin;
2208
- const stdout = process.stdout;
2209
- stdin.setEncoding("utf8");
2210
- stdin.resume();
2211
- stdout.write("> ");
2212
- stdin.on("data", (data) => {
2213
- const line = data.trim();
2214
- const parts = line.split(/\s+/);
2215
- const command = parts[0];
2216
- const arg = parts[1];
2217
- switch (command) {
2218
- case "quit":
2219
- case "exit":
2220
- case "q":
2221
- console.log("👋 Goodbye!");
2222
- process.exit(0);
2223
- break;
2224
- case "inspect":
2225
- if (!arg) console.log("❌ Usage: inspect <type-name>");
2226
- else {
2227
- const info = typeIndex.get(arg);
2228
- if (info) {
2229
- console.log(`\n🔍 ${info.displayName}`);
2230
- console.log(` ${"─".repeat(50)}`);
2231
- console.log(` Type ID: 0x${info.id.toString(16)}`);
2232
- console.log(` Kind: ${info.kind}`);
2233
- console.log("");
2234
- } else console.log(`❌ Type "${arg}" not found`);
2235
- }
2236
- break;
2237
- case "ids":
2238
- console.log("\n📋 All Type IDs:");
2239
- console.log(` ${"─".repeat(50)}`);
2240
- for (const [name, info] of typeIndex) {
2241
- if (name.includes(".")) continue;
2242
- console.log(` 0x${info.id.toString(16).padStart(16, "0")} ${info.displayName}`);
2243
- }
2244
- console.log("");
2245
- break;
2246
- case "export": {
2247
- const exportData = {
2248
- sourceFile: inputFile,
2249
- types: Array.from(typeIndex.entries()).filter(([name]) => !name.includes(".")).map(([name, info]) => ({
2250
- name,
2251
- displayName: info.displayName,
2252
- typeId: `0x${info.id.toString(16)}`,
2253
- kind: info.kind
2254
- }))
2255
- };
2256
- console.log(JSON.stringify(exportData, null, 2));
2257
- break;
2258
- }
2259
- case "help":
2260
- case "h":
2261
- console.log("\n💡 Commands:");
2262
- console.log(" inspect <type> - Show detailed information about a type");
2263
- console.log(" ids - List all type IDs");
2264
- console.log(" export - Export schema info as JSON");
2265
- console.log(" quit - Exit interactive mode");
2266
- console.log("");
2267
- break;
2268
- default: if (line) {
2269
- console.log(`❌ Unknown command: ${command}`);
2270
- console.log(" Type \"help\" for available commands");
62
+ if (values.version) {
63
+ console.log(VERSION);
64
+ process.exit(0);
65
+ }
66
+ if (values.help || positionals.length === 0) {
67
+ printMainUsage();
68
+ process.exit(0);
69
+ }
70
+ const command = positionals[0];
71
+ const args = process.argv.slice(3);
72
+ switch (command) {
73
+ case "gen":
74
+ await import("./cli-gen-aCkffW1Z.js").then((m) => m.run(args));
75
+ break;
76
+ case "json":
77
+ await import("./cli-DGBgLdGK.js").then((m) => m.run(args));
78
+ break;
79
+ case "compat":
80
+ await import("./cli-DlZBZozW.js").then((m) => m.run(args));
81
+ break;
82
+ case "audit":
83
+ await import("./cli-audit-j58Eyd5d.js").then((m) => m.run(args));
84
+ break;
85
+ case "bench":
86
+ await import("./cli-bench-bkR1vGK8.js").then((m) => m.run(args));
87
+ break;
88
+ case "help":
89
+ if (positionals[1]) {
90
+ args.push("--help");
91
+ switch (positionals[1]) {
92
+ case "gen":
93
+ await import("./cli-gen-aCkffW1Z.js").then((m) => m.run(args));
94
+ break;
95
+ case "json":
96
+ await import("./cli-DGBgLdGK.js").then((m) => m.run(args));
97
+ break;
98
+ case "compat":
99
+ await import("./cli-DlZBZozW.js").then((m) => m.run(args));
100
+ break;
101
+ case "audit":
102
+ await import("./cli-audit-j58Eyd5d.js").then((m) => m.run(args));
103
+ break;
104
+ case "bench":
105
+ await import("./cli-bench-bkR1vGK8.js").then((m) => m.run(args));
106
+ break;
107
+ default:
108
+ console.error(`Unknown command: ${positionals[1]}`);
109
+ process.exit(1);
2271
110
  }
2272
- }
2273
- stdout.write("> ");
2274
- });
2275
- await new Promise(() => {});
2276
- } catch (err) {
2277
- console.error("Error:", err.message);
2278
- process.exit(1);
2279
- } finally {
2280
- rmSync(tmpDir, {
2281
- recursive: true,
2282
- force: true
2283
- });
111
+ } else printMainUsage();
112
+ break;
113
+ default:
114
+ console.error(`Unknown command: ${command}`);
115
+ printMainUsage();
116
+ process.exit(1);
2284
117
  }
2285
118
  }
2286
- /**
2287
- * Convert string to PascalCase
2288
- */
2289
- function toPascalCase(str) {
2290
- return str.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
2291
- }
119
+ main().catch((err) => {
120
+ console.error("Error:", err.message);
121
+ process.exit(1);
122
+ });
2292
123
 
2293
124
  //#endregion
2294
125
  export { };