@naeemo/capnp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,328 +1,1704 @@
1
1
  #!/usr/bin/env node
2
2
  #!/usr/bin/env node
3
- import { readFileSync, writeFileSync } from "node:fs";
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";
4
7
  import { parseArgs } from "node:util";
5
8
 
6
- //#region src/codegen/enum-gen.ts
9
+ //#region src/codegen/generator.ts
10
+ const DEFAULT_OPTIONS = { runtimeImportPath: "@naeemo/capnp" };
7
11
  /**
8
- * Enum generator
12
+ * CodeGeneratorRequest 生成 TypeScript 代码
9
13
  */
10
- function generateEnum(enum_, lines) {
11
- lines.push(`export enum ${enum_.name} {`);
12
- for (const value of enum_.values) lines.push(` ${value.name} = ${value.index},`);
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);");
13
48
  lines.push("}");
14
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");
15
78
  }
16
-
17
- //#endregion
18
- //#region src/codegen/type-utils.ts
19
- function isPointerType(type) {
20
- if (typeof type === "string") return type === "Text" || type === "Data";
21
- return type.kind === "list" || type.kind === "struct";
22
- }
23
- function getTypeSize(type) {
24
- if (typeof type !== "string") return 8;
25
- switch (type) {
26
- case "Void": return 0;
27
- case "Bool": return 1;
28
- case "Int8":
29
- case "UInt8": return 1;
30
- case "Int16":
31
- case "UInt16": return 2;
32
- case "Int32":
33
- case "UInt32":
34
- case "Float32": return 4;
35
- case "Int64":
36
- case "UInt64":
37
- case "Float64": return 8;
38
- default: return 8;
39
- }
40
- }
41
- function mapTypeToTs(type) {
42
- if (typeof type !== "string") {
43
- if (type.kind === "list") return `${mapTypeToTs(type.elementType)}[]`;
44
- return type.name;
45
- }
46
- switch (type) {
47
- case "Void": return "void";
48
- case "Bool": return "boolean";
49
- case "Int8":
50
- case "Int16":
51
- case "Int32":
52
- case "UInt8":
53
- case "UInt16":
54
- case "UInt32":
55
- case "Float32":
56
- case "Float64": return "number";
57
- case "Int64":
58
- case "UInt64": return "bigint";
59
- case "Text": return "string";
60
- case "Data": return "Uint8Array";
61
- default: return "unknown";
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 */ }`;
62
603
  }
63
604
  }
64
- function getGetterMethod(type) {
65
- if (typeof type !== "string") {
66
- if (type.kind === "list") return "getList";
67
- return "getStruct";
68
- }
69
- switch (type) {
70
- case "Void": return "getVoid";
71
- case "Bool": return "getBool";
72
- case "Int8": return "getInt8";
73
- case "Int16": return "getInt16";
74
- case "Int32": return "getInt32";
75
- case "Int64": return "getInt64";
76
- case "UInt8": return "getUint8";
77
- case "UInt16": return "getUint16";
78
- case "UInt32": return "getUint32";
79
- case "UInt64": return "getUint64";
80
- case "Float32": return "getFloat32";
81
- case "Float64": return "getFloat64";
82
- case "Text": return "getText";
83
- case "Data": return "getData";
84
- default: return "getUnknown";
85
- }
86
- }
87
- function getSetterMethod(type) {
88
- if (typeof type !== "string") {
89
- if (type.kind === "list") return "initList";
90
- return "initStruct";
91
- }
92
- switch (type) {
93
- case "Void": return "setVoid";
94
- case "Bool": return "setBool";
95
- case "Int8": return "setInt8";
96
- case "Int16": return "setInt16";
97
- case "Int32": return "setInt32";
98
- case "Int64": return "setInt64";
99
- case "UInt8": return "setUint8";
100
- case "UInt16": return "setUint16";
101
- case "UInt32": return "setUint32";
102
- case "UInt64": return "setUint64";
103
- case "Float32": return "setFloat32";
104
- case "Float64": return "setFloat64";
105
- case "Text": return "setText";
106
- case "Data": return "setData";
107
- default: return "setUnknown";
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";
108
626
  }
109
627
  }
628
+ /**
629
+ * 首字母大写
630
+ */
110
631
  function capitalize(str) {
111
632
  return str.charAt(0).toUpperCase() + str.slice(1);
112
633
  }
113
-
114
- //#endregion
115
- //#region src/codegen/struct-gen.ts
116
- function generateStruct(struct, lines) {
117
- let dataWords = 0;
118
- let pointerCount = 0;
119
- let dataOffset = 0;
120
- for (const field of struct.fields) if (isPointerType(field.type)) pointerCount++;
121
- else dataOffset += getTypeSize(field.type);
122
- dataWords = Math.ceil(dataOffset / 8);
123
- lines.push(`export interface ${struct.name} {`);
124
- for (const field of struct.fields) lines.push(` ${field.name}: ${mapTypeToTs(field.type)};`);
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},`);
125
642
  lines.push("}");
126
- lines.push("");
127
- generateReader(struct, dataWords, pointerCount, lines);
128
- generateBuilder(struct, dataWords, pointerCount, lines);
643
+ return lines.join("\n");
129
644
  }
130
- function generateReader(struct, _dataWords, _pointerCount, lines) {
131
- lines.push(`export class ${struct.name}Reader {`);
132
- lines.push(" private reader: StructReader;");
133
- lines.push("");
134
- lines.push(" constructor(reader: StructReader) {");
135
- lines.push(" this.reader = reader;");
136
- lines.push(" }");
137
- lines.push("");
138
- let dataOffset = 0;
139
- let pointerIndex = 0;
140
- for (const field of struct.fields) {
141
- const tsType = mapTypeToTs(field.type);
142
- if (isPointerType(field.type)) {
143
- lines.push(` get ${field.name}(): ${tsType} {`);
144
- lines.push(` return this.reader.${getGetterMethod(field.type)}(${pointerIndex});`);
145
- lines.push(" }");
146
- pointerIndex++;
147
- } else {
148
- lines.push(` get ${field.name}(): ${tsType} {`);
149
- lines.push(` return this.reader.${getGetterMethod(field.type)}(${dataOffset});`);
150
- lines.push(" }");
151
- dataOffset += getTypeSize(field.type);
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)}[]`;
152
669
  }
153
- lines.push("");
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;`);
154
728
  }
155
729
  lines.push("}");
156
730
  lines.push("");
157
- }
158
- function generateBuilder(struct, dataWords, pointerCount, lines) {
159
- lines.push(`export class ${struct.name}Builder {`);
160
- lines.push(" private builder: StructBuilder;");
731
+ lines.push(`// ${interfaceName} Server Stub`);
732
+ lines.push(`export class ${interfaceName}Stub {`);
733
+ lines.push(` private server: ${interfaceName}Server;`);
161
734
  lines.push("");
162
- lines.push(" constructor(builder: StructBuilder) {");
163
- lines.push(" this.builder = builder;");
735
+ lines.push(` constructor(server: ${interfaceName}Server) {`);
736
+ lines.push(" this.server = server;");
164
737
  lines.push(" }");
165
738
  lines.push("");
166
- lines.push(` static create(message: MessageBuilder): ${struct.name}Builder {`);
167
- lines.push(` const root = message.initRoot(${dataWords}, ${pointerCount});`);
168
- lines.push(` return new ${struct.name}Builder(root);`);
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(" }");
169
753
  lines.push(" }");
170
754
  lines.push("");
171
- let dataOffset = 0;
172
- let pointerIndex = 0;
173
- for (const field of struct.fields) {
174
- const tsType = mapTypeToTs(field.type);
175
- const method = getSetterMethod(field.type);
176
- if (isPointerType(field.type)) {
177
- lines.push(` set${capitalize(field.name)}(value: ${tsType}): void {`);
178
- lines.push(` this.builder.${method}(${pointerIndex}, value);`);
179
- lines.push(" }");
180
- pointerIndex++;
181
- } else {
182
- lines.push(` set${capitalize(field.name)}(value: ${tsType}): void {`);
183
- lines.push(` this.builder.${method}(${dataOffset}, value);`);
184
- lines.push(" }");
185
- dataOffset += getTypeSize(field.type);
186
- }
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(" }");
187
782
  lines.push("");
188
783
  }
189
784
  lines.push("}");
190
- 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);
191
794
  }
192
795
 
193
796
  //#endregion
194
- //#region src/codegen/generator-v2.ts
797
+ //#region src/core/pointer.ts
195
798
  /**
196
- * Main code generator v2
799
+ * Cap'n Proto 指针编解码
800
+ * 纯 TypeScript 实现
197
801
  */
198
- const DEFAULT_OPTIONS = { runtimeImportPath: "@naeemo/capnp" };
199
- function generateCode(schema, options) {
200
- const opts = {
201
- ...DEFAULT_OPTIONS,
202
- ...options
203
- };
204
- const lines = [];
205
- lines.push("// Generated by capnp-ts-codegen");
206
- lines.push("// DO NOT EDIT MANUALLY");
207
- lines.push("");
208
- lines.push(`import { MessageReader, MessageBuilder, StructReader, StructBuilder } from "${opts.runtimeImportPath}";`);
209
- lines.push("");
210
- for (const enum_ of schema.enums) generateEnum(enum_, lines);
211
- for (const struct of schema.structs) generateStruct(struct, lines);
212
- return lines.join("\n");
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
+ }
213
857
  }
214
858
 
215
859
  //#endregion
216
- //#region src/codegen/parser-v2.ts
217
- const PRIMITIVE_TYPES = new Set([
218
- "Void",
219
- "Bool",
220
- "Int8",
221
- "Int16",
222
- "Int32",
223
- "Int64",
224
- "UInt8",
225
- "UInt16",
226
- "UInt32",
227
- "UInt64",
228
- "Float32",
229
- "Float64",
230
- "Text",
231
- "Data"
232
- ]);
233
- function isPrimitive(type) {
234
- return PRIMITIVE_TYPES.has(type);
235
- }
236
- /**
237
- * 解析 Cap'n Proto schema
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
+ const low = BigInt(this.view.getUint32(byteOffset, true));
913
+ return BigInt(this.view.getUint32(byteOffset + 4, true)) << BigInt(32) | low;
914
+ }
915
+ /**
916
+ * 设置字(64位)
917
+ */
918
+ setWord(wordOffset, value) {
919
+ const byteOffset = wordOffset * WORD_SIZE;
920
+ this.view.setUint32(byteOffset, Number(value & BigInt(4294967295)), true);
921
+ this.view.setUint32(byteOffset + 4, Number(value >> BigInt(32)), true);
922
+ }
923
+ /**
924
+ * 获取原始 buffer(只读到 _size)
925
+ */
926
+ asUint8Array() {
927
+ return new Uint8Array(this.buffer, 0, this._size);
928
+ }
929
+ /**
930
+ * 获取底层 ArrayBuffer
931
+ */
932
+ getArrayBuffer() {
933
+ return this.buffer;
934
+ }
935
+ /**
936
+ * 获取字数量
937
+ */
938
+ get wordCount() {
939
+ return this._size / WORD_SIZE;
940
+ }
941
+ /**
942
+ * 获取字节数量
943
+ */
944
+ get byteLength() {
945
+ return this._size;
946
+ }
947
+ /**
948
+ * 获取 DataView
949
+ */
950
+ get dataView() {
951
+ return this.view;
952
+ }
953
+ };
954
+
955
+ //#endregion
956
+ //#region src/core/list.ts
957
+ /**
958
+ * ListReader - 读取列表
959
+ */
960
+ var ListReader = class {
961
+ segment;
962
+ startOffset;
963
+ segmentIndex;
964
+ constructor(message, segmentIndex, elementSize, elementCount, structSize, wordOffset) {
965
+ this.message = message;
966
+ this.elementSize = elementSize;
967
+ this.elementCount = elementCount;
968
+ this.structSize = structSize;
969
+ this.segmentIndex = segmentIndex;
970
+ this.segment = message.getSegment(segmentIndex);
971
+ this.startOffset = wordOffset;
972
+ }
973
+ /**
974
+ * 列表长度
975
+ */
976
+ get length() {
977
+ return this.elementCount;
978
+ }
979
+ /**
980
+ * 获取元素(基础类型)
981
+ */
982
+ getPrimitive(index) {
983
+ if (index < 0 || index >= this.elementCount) throw new RangeError("Index out of bounds");
984
+ switch (this.elementSize) {
985
+ case ElementSize.BIT: {
986
+ const byteOffset = Math.floor(index / 8);
987
+ const bitInByte = index % 8;
988
+ return (this.segment.dataView.getUint8(this.startOffset * WORD_SIZE + byteOffset) & 1 << bitInByte) !== 0 ? 1 : 0;
989
+ }
990
+ case ElementSize.BYTE: return this.segment.dataView.getUint8(this.startOffset * WORD_SIZE + index);
991
+ case ElementSize.TWO_BYTES: return this.segment.dataView.getUint16(this.startOffset * WORD_SIZE + index * 2, true);
992
+ case ElementSize.FOUR_BYTES: return this.segment.dataView.getUint32(this.startOffset * WORD_SIZE + index * 4, true);
993
+ case ElementSize.EIGHT_BYTES: {
994
+ const offset = this.startOffset * WORD_SIZE + index * 8;
995
+ const low = BigInt(this.segment.dataView.getUint32(offset, true));
996
+ return BigInt(this.segment.dataView.getUint32(offset + 4, true)) << BigInt(32) | low;
997
+ }
998
+ default: throw new Error(`Unsupported element size: ${this.elementSize}`);
999
+ }
1000
+ }
1001
+ /**
1002
+ * 获取结构元素
1003
+ */
1004
+ getStruct(index) {
1005
+ if (!this.structSize) throw new Error("Not a struct list");
1006
+ const { dataWords, pointerCount } = this.structSize;
1007
+ const size = dataWords + pointerCount;
1008
+ const offset = this.startOffset + index * size;
1009
+ return new StructReader(this.message, this.segmentIndex, offset, dataWords, pointerCount);
1010
+ }
1011
+ /**
1012
+ * 迭代器
1013
+ */
1014
+ *[Symbol.iterator]() {
1015
+ for (let i = 0; i < this.elementCount; i++) yield this.getPrimitive(i);
1016
+ }
1017
+ };
1018
+
1019
+ //#endregion
1020
+ //#region src/core/message-reader.ts
1021
+ /**
1022
+ * Cap'n Proto MessageReader
1023
+ * 纯 TypeScript 实现
1024
+ */
1025
+ var MessageReader = class {
1026
+ segments;
1027
+ constructor(buffer) {
1028
+ const uint8Array = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer;
1029
+ this.segments = [];
1030
+ if (uint8Array.byteLength < 8) return;
1031
+ const view = new DataView(uint8Array.buffer, uint8Array.byteOffset, uint8Array.byteLength);
1032
+ const firstWordLow = view.getUint32(0, true);
1033
+ const firstWordHigh = view.getUint32(4, true);
1034
+ const segmentCount = (firstWordLow & 4294967295) + 1;
1035
+ const firstSegmentSize = firstWordHigh;
1036
+ let offset = 8;
1037
+ const segmentSizes = [firstSegmentSize];
1038
+ for (let i = 1; i < segmentCount; i++) {
1039
+ if (offset + 4 > uint8Array.byteLength) {
1040
+ this.segments = [];
1041
+ return;
1042
+ }
1043
+ segmentSizes.push(view.getUint32(offset, true));
1044
+ offset += 4;
1045
+ }
1046
+ offset = offset + 7 & -8;
1047
+ if (offset > uint8Array.byteLength) {
1048
+ this.segments = [];
1049
+ return;
1050
+ }
1051
+ this.segments = [];
1052
+ for (const size of segmentSizes) {
1053
+ if (offset + size * WORD_SIZE > uint8Array.byteLength) break;
1054
+ const segmentBuffer = uint8Array.slice(offset, offset + size * WORD_SIZE);
1055
+ this.segments.push(Segment.fromBuffer(segmentBuffer.buffer));
1056
+ offset += size * WORD_SIZE;
1057
+ }
1058
+ }
1059
+ /**
1060
+ * 获取根结构
1061
+ */
1062
+ getRoot(_dataWords, _pointerCount) {
1063
+ const segment = this.segments[0];
1064
+ const ptr = decodePointer(segment.getWord(0));
1065
+ if (ptr.tag === PointerTag.STRUCT) {
1066
+ const structPtr = ptr;
1067
+ const dataOffset = 1 + structPtr.offset;
1068
+ return new StructReader(this, 0, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1069
+ }
1070
+ if (ptr.tag === PointerTag.FAR) {
1071
+ const farPtr = ptr;
1072
+ const targetSegment = this.getSegment(farPtr.targetSegment);
1073
+ if (!targetSegment) throw new Error(`Far pointer references non-existent segment ${farPtr.targetSegment}`);
1074
+ if (farPtr.doubleFar) {
1075
+ const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1076
+ if (landingPadPtr.tag !== PointerTag.FAR) throw new Error("Double-far landing pad is not a far pointer");
1077
+ const innerFarPtr = landingPadPtr;
1078
+ const finalSegment = this.getSegment(innerFarPtr.targetSegment);
1079
+ if (!finalSegment) throw new Error(`Double-far references non-existent segment ${innerFarPtr.targetSegment}`);
1080
+ const structPtr = decodePointer(finalSegment.getWord(innerFarPtr.targetOffset));
1081
+ const dataOffset = innerFarPtr.targetOffset + 1 + structPtr.offset;
1082
+ return new StructReader(this, innerFarPtr.targetSegment, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1083
+ }
1084
+ const structPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1085
+ const dataOffset = farPtr.targetOffset + 1 + structPtr.offset;
1086
+ return new StructReader(this, farPtr.targetSegment, dataOffset, structPtr.dataWords, structPtr.pointerCount);
1087
+ }
1088
+ throw new Error(`Root pointer is not a struct or far pointer: ${ptr.tag}`);
1089
+ }
1090
+ /**
1091
+ * 获取段
1092
+ */
1093
+ getSegment(index) {
1094
+ return this.segments[index];
1095
+ }
1096
+ /**
1097
+ * 解析指针,处理 far pointer 间接寻址
1098
+ * 返回 { segmentIndex, wordOffset, pointer },其中 pointer 是实际的 struct/list 指针
1099
+ */
1100
+ resolvePointer(segmentIndex, wordOffset) {
1101
+ const segment = this.getSegment(segmentIndex);
1102
+ if (!segment) return null;
1103
+ const ptrValue = segment.getWord(wordOffset);
1104
+ if (ptrValue === 0n) return null;
1105
+ const ptr = decodePointer(ptrValue);
1106
+ if (ptr.tag === PointerTag.STRUCT || ptr.tag === PointerTag.LIST) return {
1107
+ segmentIndex,
1108
+ wordOffset: wordOffset + 1 + ptr.offset,
1109
+ pointer: ptr
1110
+ };
1111
+ if (ptr.tag === PointerTag.FAR) {
1112
+ const farPtr = ptr;
1113
+ const targetSegment = this.getSegment(farPtr.targetSegment);
1114
+ if (!targetSegment) return null;
1115
+ if (farPtr.doubleFar) {
1116
+ const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1117
+ if (landingPadPtr.tag !== PointerTag.FAR) return null;
1118
+ const innerFarPtr = landingPadPtr;
1119
+ const finalSegment = this.getSegment(innerFarPtr.targetSegment);
1120
+ if (!finalSegment) return null;
1121
+ const finalPtr = decodePointer(finalSegment.getWord(innerFarPtr.targetOffset));
1122
+ if (finalPtr.tag !== PointerTag.STRUCT && finalPtr.tag !== PointerTag.LIST) return null;
1123
+ const targetOffset = innerFarPtr.targetOffset + 1 + finalPtr.offset;
1124
+ return {
1125
+ segmentIndex: innerFarPtr.targetSegment,
1126
+ wordOffset: targetOffset,
1127
+ pointer: finalPtr
1128
+ };
1129
+ }
1130
+ const landingPadPtr = decodePointer(targetSegment.getWord(farPtr.targetOffset));
1131
+ if (landingPadPtr.tag !== PointerTag.STRUCT && landingPadPtr.tag !== PointerTag.LIST) return null;
1132
+ const targetOffset = farPtr.targetOffset + 1 + landingPadPtr.offset;
1133
+ return {
1134
+ segmentIndex: farPtr.targetSegment,
1135
+ wordOffset: targetOffset,
1136
+ pointer: landingPadPtr
1137
+ };
1138
+ }
1139
+ return null;
1140
+ }
1141
+ /**
1142
+ * 段数量
1143
+ */
1144
+ get segmentCount() {
1145
+ return this.segments.length;
1146
+ }
1147
+ };
1148
+ /**
1149
+ * 结构读取器
1150
+ */
1151
+ var StructReader = class StructReader {
1152
+ constructor(message, segmentIndex, wordOffset, dataWords, pointerCount) {
1153
+ this.message = message;
1154
+ this.segmentIndex = segmentIndex;
1155
+ this.wordOffset = wordOffset;
1156
+ this.dataWords = dataWords;
1157
+ this.pointerCount = pointerCount;
1158
+ }
1159
+ /**
1160
+ * 获取 bool 字段
1161
+ */
1162
+ getBool(bitOffset) {
1163
+ const byteOffset = Math.floor(bitOffset / 8);
1164
+ const bitInByte = bitOffset % 8;
1165
+ return (this.message.getSegment(this.segmentIndex).dataView.getUint8(this.wordOffset * WORD_SIZE + byteOffset) & 1 << bitInByte) !== 0;
1166
+ }
1167
+ /**
1168
+ * 获取 int8 字段
1169
+ */
1170
+ getInt8(byteOffset) {
1171
+ return this.message.getSegment(this.segmentIndex).dataView.getInt8(this.wordOffset * WORD_SIZE + byteOffset);
1172
+ }
1173
+ /**
1174
+ * 获取 int16 字段
1175
+ */
1176
+ getInt16(byteOffset) {
1177
+ return this.message.getSegment(this.segmentIndex).dataView.getInt16(this.wordOffset * WORD_SIZE + byteOffset, true);
1178
+ }
1179
+ /**
1180
+ * 获取 int32 字段
1181
+ */
1182
+ getInt32(byteOffset) {
1183
+ return this.message.getSegment(this.segmentIndex).dataView.getInt32(this.wordOffset * WORD_SIZE + byteOffset, true);
1184
+ }
1185
+ /**
1186
+ * 获取 int64 字段
1187
+ */
1188
+ getInt64(byteOffset) {
1189
+ const segment = this.message.getSegment(this.segmentIndex);
1190
+ const offset = this.wordOffset * WORD_SIZE + byteOffset;
1191
+ const low = BigInt(segment.dataView.getUint32(offset, true));
1192
+ return BigInt(segment.dataView.getInt32(offset + 4, true)) << BigInt(32) | low;
1193
+ }
1194
+ /**
1195
+ * 获取 uint8 字段
1196
+ */
1197
+ getUint8(byteOffset) {
1198
+ return this.message.getSegment(this.segmentIndex).dataView.getUint8(this.wordOffset * WORD_SIZE + byteOffset);
1199
+ }
1200
+ /**
1201
+ * 获取 uint16 字段
1202
+ */
1203
+ getUint16(byteOffset) {
1204
+ return this.message.getSegment(this.segmentIndex).dataView.getUint16(this.wordOffset * WORD_SIZE + byteOffset, true);
1205
+ }
1206
+ /**
1207
+ * 获取 uint32 字段
1208
+ */
1209
+ getUint32(byteOffset) {
1210
+ return this.message.getSegment(this.segmentIndex).dataView.getUint32(this.wordOffset * WORD_SIZE + byteOffset, true);
1211
+ }
1212
+ /**
1213
+ * 获取 uint64 字段
1214
+ */
1215
+ getUint64(byteOffset) {
1216
+ const segment = this.message.getSegment(this.segmentIndex);
1217
+ const offset = this.wordOffset * WORD_SIZE + byteOffset;
1218
+ const low = BigInt(segment.dataView.getUint32(offset, true));
1219
+ return BigInt(segment.dataView.getUint32(offset + 4, true)) << BigInt(32) | low;
1220
+ }
1221
+ /**
1222
+ * 获取 float32 字段
1223
+ */
1224
+ getFloat32(byteOffset) {
1225
+ return this.message.getSegment(this.segmentIndex).dataView.getFloat32(this.wordOffset * WORD_SIZE + byteOffset, true);
1226
+ }
1227
+ /**
1228
+ * 获取 float64 字段
1229
+ */
1230
+ getFloat64(byteOffset) {
1231
+ return this.message.getSegment(this.segmentIndex).dataView.getFloat64(this.wordOffset * WORD_SIZE + byteOffset, true);
1232
+ }
1233
+ /**
1234
+ * 获取文本字段
1235
+ */
1236
+ getText(pointerIndex) {
1237
+ const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1238
+ const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1239
+ if (!resolved) return "";
1240
+ const { segmentIndex, wordOffset, pointer } = resolved;
1241
+ if (pointer.tag !== PointerTag.LIST) return "";
1242
+ const listPtr = pointer;
1243
+ const segment = this.message.getSegment(segmentIndex);
1244
+ const byteLength = listPtr.elementCount > 0 ? listPtr.elementCount - 1 : 0;
1245
+ if (byteLength === 0) return "";
1246
+ const bytes = new Uint8Array(segment.dataView.buffer, wordOffset * WORD_SIZE, byteLength);
1247
+ return new TextDecoder().decode(bytes);
1248
+ }
1249
+ /**
1250
+ * 获取嵌套结构
1251
+ */
1252
+ getStruct(pointerIndex, _dataWords, _pointerCount) {
1253
+ const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1254
+ const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1255
+ if (!resolved) return void 0;
1256
+ const { segmentIndex, wordOffset, pointer } = resolved;
1257
+ if (pointer.tag !== PointerTag.STRUCT) return void 0;
1258
+ const structPtr = pointer;
1259
+ return new StructReader(this.message, segmentIndex, wordOffset, structPtr.dataWords, structPtr.pointerCount);
1260
+ }
1261
+ /**
1262
+ * 获取列表
1263
+ */
1264
+ getList(pointerIndex, _elementSize, structSize) {
1265
+ const ptrOffset = this.wordOffset + this.dataWords + pointerIndex;
1266
+ const resolved = this.message.resolvePointer(this.segmentIndex, ptrOffset);
1267
+ if (!resolved) return void 0;
1268
+ const { segmentIndex, wordOffset, pointer } = resolved;
1269
+ if (pointer.tag !== PointerTag.LIST) return void 0;
1270
+ const listPtr = pointer;
1271
+ let targetOffset = wordOffset;
1272
+ let elementCount = listPtr.elementCount;
1273
+ let actualStructSize = structSize;
1274
+ const segment = this.message.getSegment(segmentIndex);
1275
+ if (listPtr.elementSize === ElementSize.COMPOSITE) {
1276
+ const tagWord = segment.getWord(targetOffset);
1277
+ elementCount = Number(tagWord & BigInt(4294967295));
1278
+ actualStructSize = {
1279
+ dataWords: Number(tagWord >> BigInt(32) & BigInt(65535)),
1280
+ pointerCount: Number(tagWord >> BigInt(48) & BigInt(65535))
1281
+ };
1282
+ targetOffset += 1;
1283
+ }
1284
+ return new ListReader(this.message, segmentIndex, listPtr.elementSize, elementCount, actualStructSize, targetOffset);
1285
+ }
1286
+ };
1287
+
1288
+ //#endregion
1289
+ //#region src/schema/schema-reader.ts
1290
+ /**
1291
+ * Cap'n Proto 编译后 Schema 的 TypeScript Reader
1292
+ * 基于官方 schema.capnp 手动编写
238
1293
  *
239
- * 支持的语法:
240
- * - Struct 定义
241
- * - Enum 定义
242
- * - 基础类型字段
243
- * - List 类型
244
- * - 嵌套 struct 引用
1294
+ * 这是自举的基础:我们需要先能读取 schema 才能生成 schema 的代码
245
1295
  *
246
- * 不支持的语法(会忽略或报错):
247
- * - Union
248
- * - Group
249
- * - Interface
250
- * - Const
251
- * - Annotation
252
- * - 默认值
253
- */
254
- function parseSchemaV2(source) {
255
- const structs = [];
256
- const enums = [];
257
- const cleanSource = source.replace(/#.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
258
- const structRegex = /struct\s+(\w+)\s*\{([^}]*)\}/g;
259
- let match;
260
- while ((match = structRegex.exec(cleanSource)) !== null) {
261
- const name = match[1];
262
- const body = match[2];
263
- const fields = parseFields(body);
264
- structs.push({
265
- name,
266
- fields
1296
+ * 结构信息来自: capnp compile -ocapnp schema.capnp
1297
+ */
1298
+ var NodeReader = class {
1299
+ constructor(reader) {
1300
+ this.reader = reader;
1301
+ }
1302
+ get id() {
1303
+ return this.reader.getUint64(0);
1304
+ }
1305
+ get displayName() {
1306
+ return this.reader.getText(0);
1307
+ }
1308
+ get displayNamePrefixLength() {
1309
+ return this.reader.getUint32(8);
1310
+ }
1311
+ get scopeId() {
1312
+ return this.reader.getUint64(16);
1313
+ }
1314
+ /** union tag 在 bits [96, 112) = bytes [12, 14) */
1315
+ get unionTag() {
1316
+ return this.reader.getUint16(12);
1317
+ }
1318
+ get isFile() {
1319
+ return this.unionTag === 0;
1320
+ }
1321
+ get isStruct() {
1322
+ return this.unionTag === 1;
1323
+ }
1324
+ get isEnum() {
1325
+ return this.unionTag === 2;
1326
+ }
1327
+ get isInterface() {
1328
+ return this.unionTag === 3;
1329
+ }
1330
+ get isConst() {
1331
+ return this.unionTag === 4;
1332
+ }
1333
+ get isAnnotation() {
1334
+ return this.unionTag === 5;
1335
+ }
1336
+ get structDataWordCount() {
1337
+ return this.reader.getUint16(14);
1338
+ }
1339
+ get structPointerCount() {
1340
+ return this.reader.getUint16(24);
1341
+ }
1342
+ get structPreferredListEncoding() {
1343
+ return this.reader.getUint16(26);
1344
+ }
1345
+ get structIsGroup() {
1346
+ return this.reader.getBool(224);
1347
+ }
1348
+ get structDiscriminantCount() {
1349
+ return this.reader.getUint16(30);
1350
+ }
1351
+ get structDiscriminantOffset() {
1352
+ return this.reader.getUint32(32);
1353
+ }
1354
+ get structFields() {
1355
+ const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1356
+ dataWords: 3,
1357
+ pointerCount: 4
267
1358
  });
1359
+ if (!listReader) return [];
1360
+ const fields = [];
1361
+ for (let i = 0; i < listReader.length; i++) {
1362
+ const field = new FieldReader(listReader.getStruct(i));
1363
+ if (!field.name && i > 0) break;
1364
+ fields.push(field);
1365
+ }
1366
+ return fields;
268
1367
  }
269
- const enumRegex = /enum\s+(\w+)\s*\{([^}]*)\}/g;
270
- while ((match = enumRegex.exec(cleanSource)) !== null) {
271
- const name = match[1];
272
- const body = match[2];
273
- const values = parseEnumValues(body);
274
- enums.push({
275
- name,
276
- values
1368
+ get enumEnumerants() {
1369
+ const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1370
+ dataWords: 1,
1371
+ pointerCount: 2
277
1372
  });
1373
+ if (!listReader) return [];
1374
+ const enumerants = [];
1375
+ for (let i = 0; i < Math.min(listReader.length, 10); i++) try {
1376
+ const enumerant = new EnumerantReader(listReader.getStruct(i));
1377
+ if (!enumerant.name) break;
1378
+ enumerants.push(enumerant);
1379
+ } catch (_e) {
1380
+ break;
1381
+ }
1382
+ return enumerants;
278
1383
  }
279
- return {
280
- structs,
281
- enums
282
- };
283
- }
284
- function parseFields(body) {
285
- const fields = [];
286
- const fieldRegex = /(\w+)\s*@(\d+)\s*:\s*([^;]+);/g;
287
- let match;
288
- while ((match = fieldRegex.exec(body)) !== null) {
289
- const name = match[1];
290
- const index = Number.parseInt(match[2]);
291
- const type = parseType(match[3].trim());
292
- fields.push({
293
- name,
294
- index,
295
- type
1384
+ get interfaceMethods() {
1385
+ const listReader = this.reader.getList(3, ElementSize.INLINE_COMPOSITE, {
1386
+ dataWords: 5,
1387
+ pointerCount: 2
296
1388
  });
1389
+ if (!listReader) return [];
1390
+ const methods = [];
1391
+ for (let i = 0; i < listReader.length; i++) try {
1392
+ const method = new MethodReader(listReader.getStruct(i));
1393
+ if (!method.name && i > 0) break;
1394
+ methods.push(method);
1395
+ } catch (_e) {
1396
+ break;
1397
+ }
1398
+ return methods;
297
1399
  }
298
- return fields.sort((a, b) => a.index - b.index);
299
- }
300
- function parseType(typeStr) {
301
- const listMatch = typeStr.match(/^List\((.+)\)$/);
302
- if (listMatch) return {
303
- kind: "list",
304
- elementType: parseType(listMatch[1].trim())
305
- };
306
- if (isPrimitive(typeStr)) return typeStr;
307
- return {
308
- kind: "struct",
309
- name: typeStr
310
- };
311
- }
312
- function parseEnumValues(body) {
313
- const values = [];
314
- const valueRegex = /(\w+)\s*@(\d+)\s*;/g;
315
- let match;
316
- while ((match = valueRegex.exec(body)) !== null) {
317
- const name = match[1];
318
- const index = Number.parseInt(match[2]);
319
- values.push({
320
- name,
321
- index
1400
+ get nestedNodes() {
1401
+ const listReader = this.reader.getList(1, ElementSize.INLINE_COMPOSITE, {
1402
+ dataWords: 1,
1403
+ pointerCount: 1
322
1404
  });
1405
+ if (!listReader) return [];
1406
+ const nodes = [];
1407
+ for (let i = 0; i < listReader.length; i++) {
1408
+ const itemReader = listReader.getStruct(i);
1409
+ nodes.push(new NestedNodeReader(itemReader));
1410
+ }
1411
+ return nodes;
323
1412
  }
324
- return values.sort((a, b) => a.index - b.index);
325
- }
1413
+ };
1414
+ var FieldReader = class {
1415
+ constructor(reader) {
1416
+ this.reader = reader;
1417
+ }
1418
+ get name() {
1419
+ return this.reader.getText(0);
1420
+ }
1421
+ get codeOrder() {
1422
+ return this.reader.getUint16(0);
1423
+ }
1424
+ get discriminantValue() {
1425
+ return this.reader.getUint16(2);
1426
+ }
1427
+ /** union tag 在 bits [64, 80) = bytes [8, 10) */
1428
+ get unionTag() {
1429
+ return this.reader.getUint16(8);
1430
+ }
1431
+ get isSlot() {
1432
+ return this.unionTag === 0;
1433
+ }
1434
+ get isGroup() {
1435
+ return this.unionTag === 1;
1436
+ }
1437
+ get slotOffset() {
1438
+ return this.reader.getUint32(4);
1439
+ }
1440
+ get slotType() {
1441
+ const typeReader = this.reader.getStruct(2, 3, 1);
1442
+ return typeReader ? new TypeReader(typeReader) : null;
1443
+ }
1444
+ get groupTypeId() {
1445
+ return this.reader.getUint64(16);
1446
+ }
1447
+ get defaultValue() {
1448
+ const valueReader = this.reader.getStruct(3, 2, 1);
1449
+ return valueReader ? new ValueReader(valueReader) : null;
1450
+ }
1451
+ };
1452
+ var TypeReader = class TypeReader {
1453
+ constructor(reader) {
1454
+ this.reader = reader;
1455
+ }
1456
+ get kind() {
1457
+ return TYPE_KIND_MAP[this.reader.getUint16(0)] ?? "unknown";
1458
+ }
1459
+ get isPrimitive() {
1460
+ const k = this.kind;
1461
+ return k !== "list" && k !== "enum" && k !== "struct" && k !== "interface" && k !== "anyPointer";
1462
+ }
1463
+ get listElementType() {
1464
+ if (this.kind !== "list") return null;
1465
+ const elementReader = this.reader.getStruct(0, 3, 1);
1466
+ return elementReader ? new TypeReader(elementReader) : null;
1467
+ }
1468
+ get typeId() {
1469
+ const k = this.kind;
1470
+ if (k === "enum" || k === "struct" || k === "interface") return this.reader.getUint64(8);
1471
+ return null;
1472
+ }
1473
+ };
1474
+ const TYPE_KIND_MAP = {
1475
+ 0: "void",
1476
+ 1: "bool",
1477
+ 2: "int8",
1478
+ 3: "int16",
1479
+ 4: "int32",
1480
+ 5: "int64",
1481
+ 6: "uint8",
1482
+ 7: "uint16",
1483
+ 8: "uint32",
1484
+ 9: "uint64",
1485
+ 10: "float32",
1486
+ 11: "float64",
1487
+ 12: "text",
1488
+ 13: "data",
1489
+ 14: "list",
1490
+ 15: "enum",
1491
+ 16: "struct",
1492
+ 17: "interface",
1493
+ 18: "anyPointer"
1494
+ };
1495
+ var ValueReader = class {
1496
+ constructor(reader) {
1497
+ this.reader = reader;
1498
+ }
1499
+ /** union tag 在 bits [0, 16) = bytes [0, 2) */
1500
+ get unionTag() {
1501
+ return this.reader.getUint16(0);
1502
+ }
1503
+ get isVoid() {
1504
+ return this.unionTag === 0;
1505
+ }
1506
+ get isBool() {
1507
+ return this.unionTag === 1;
1508
+ }
1509
+ get isInt8() {
1510
+ return this.unionTag === 2;
1511
+ }
1512
+ get isInt16() {
1513
+ return this.unionTag === 3;
1514
+ }
1515
+ get isInt32() {
1516
+ return this.unionTag === 4;
1517
+ }
1518
+ get isInt64() {
1519
+ return this.unionTag === 5;
1520
+ }
1521
+ get isUint8() {
1522
+ return this.unionTag === 6;
1523
+ }
1524
+ get isUint16() {
1525
+ return this.unionTag === 7;
1526
+ }
1527
+ get isUint32() {
1528
+ return this.unionTag === 8;
1529
+ }
1530
+ get isUint64() {
1531
+ return this.unionTag === 9;
1532
+ }
1533
+ get isFloat32() {
1534
+ return this.unionTag === 10;
1535
+ }
1536
+ get isFloat64() {
1537
+ return this.unionTag === 11;
1538
+ }
1539
+ get isText() {
1540
+ return this.unionTag === 12;
1541
+ }
1542
+ get isData() {
1543
+ return this.unionTag === 13;
1544
+ }
1545
+ get isList() {
1546
+ return this.unionTag === 14;
1547
+ }
1548
+ get isEnum() {
1549
+ return this.unionTag === 15;
1550
+ }
1551
+ get isStruct() {
1552
+ return this.unionTag === 16;
1553
+ }
1554
+ get isInterface() {
1555
+ return this.unionTag === 17;
1556
+ }
1557
+ get isAnyPointer() {
1558
+ return this.unionTag === 18;
1559
+ }
1560
+ get boolValue() {
1561
+ return this.reader.getBool(16);
1562
+ }
1563
+ get int8Value() {
1564
+ return this.reader.getInt8(2);
1565
+ }
1566
+ get int16Value() {
1567
+ return this.reader.getInt16(2);
1568
+ }
1569
+ get int32Value() {
1570
+ return this.reader.getInt32(4);
1571
+ }
1572
+ get int64Value() {
1573
+ return this.reader.getInt64(8);
1574
+ }
1575
+ get uint8Value() {
1576
+ return this.reader.getUint8(2);
1577
+ }
1578
+ get uint16Value() {
1579
+ return this.reader.getUint16(2);
1580
+ }
1581
+ get uint32Value() {
1582
+ return this.reader.getUint32(4);
1583
+ }
1584
+ get uint64Value() {
1585
+ return this.reader.getUint64(8);
1586
+ }
1587
+ get float32Value() {
1588
+ return this.reader.getFloat32(4);
1589
+ }
1590
+ get float64Value() {
1591
+ return this.reader.getFloat64(8);
1592
+ }
1593
+ get enumValue() {
1594
+ return this.reader.getUint16(2);
1595
+ }
1596
+ getAsNumber() {
1597
+ if (this.isInt8) return this.int8Value;
1598
+ if (this.isInt16) return this.int16Value;
1599
+ if (this.isInt32) return this.int32Value;
1600
+ if (this.isUint8) return this.uint8Value;
1601
+ if (this.isUint16) return this.uint16Value;
1602
+ if (this.isUint32) return this.uint32Value;
1603
+ if (this.isFloat32) return this.float32Value;
1604
+ if (this.isFloat64) return this.float64Value;
1605
+ if (this.isEnum) return this.enumValue;
1606
+ }
1607
+ getAsBigint() {
1608
+ if (this.isInt64) return this.int64Value;
1609
+ if (this.isUint64) return this.uint64Value;
1610
+ }
1611
+ getAsBoolean() {
1612
+ if (this.isBool) return this.boolValue;
1613
+ }
1614
+ };
1615
+ var MethodReader = class {
1616
+ constructor(reader) {
1617
+ this.reader = reader;
1618
+ }
1619
+ get name() {
1620
+ return this.reader.getText(0);
1621
+ }
1622
+ get codeOrder() {
1623
+ return this.reader.getUint16(0);
1624
+ }
1625
+ get paramStructType() {
1626
+ return this.reader.getUint64(8);
1627
+ }
1628
+ get resultStructType() {
1629
+ return this.reader.getUint64(16);
1630
+ }
1631
+ };
1632
+ var EnumerantReader = class {
1633
+ constructor(reader) {
1634
+ this.reader = reader;
1635
+ }
1636
+ get name() {
1637
+ return this.reader.getText(0);
1638
+ }
1639
+ get codeOrder() {
1640
+ return this.reader.getUint16(0);
1641
+ }
1642
+ };
1643
+ var NestedNodeReader = class {
1644
+ constructor(reader) {
1645
+ this.reader = reader;
1646
+ }
1647
+ get name() {
1648
+ return this.reader.getText(0);
1649
+ }
1650
+ get id() {
1651
+ return this.reader.getUint64(0);
1652
+ }
1653
+ };
1654
+ var CodeGeneratorRequestReader = class CodeGeneratorRequestReader {
1655
+ constructor(message) {
1656
+ this.message = message;
1657
+ }
1658
+ static fromBuffer(buffer) {
1659
+ return new CodeGeneratorRequestReader(new MessageReader(buffer));
1660
+ }
1661
+ get nodes() {
1662
+ const listReader = this.message.getRoot(0, 4).getList(0, ElementSize.INLINE_COMPOSITE, {
1663
+ dataWords: 6,
1664
+ pointerCount: 6
1665
+ });
1666
+ if (!listReader) return [];
1667
+ const nodes = [];
1668
+ for (let i = 0; i < listReader.length; i++) {
1669
+ const nodeReader = listReader.getStruct(i);
1670
+ nodes.push(new NodeReader(nodeReader));
1671
+ }
1672
+ return nodes;
1673
+ }
1674
+ get requestedFiles() {
1675
+ const listReader = this.message.getRoot(0, 4).getList(1, ElementSize.INLINE_COMPOSITE, {
1676
+ dataWords: 1,
1677
+ pointerCount: 2
1678
+ });
1679
+ if (!listReader) return [];
1680
+ const files = [];
1681
+ for (let i = 0; i < listReader.length; i++) try {
1682
+ const file = new RequestedFileReader(listReader.getStruct(i));
1683
+ if (!file.filename && files.length > 0) break;
1684
+ files.push(file);
1685
+ } catch (_e) {
1686
+ break;
1687
+ }
1688
+ return files;
1689
+ }
1690
+ };
1691
+ var RequestedFileReader = class {
1692
+ constructor(reader) {
1693
+ this.reader = reader;
1694
+ }
1695
+ get id() {
1696
+ return this.reader.getUint64(0);
1697
+ }
1698
+ get filename() {
1699
+ return this.reader.getText(0);
1700
+ }
1701
+ };
326
1702
 
327
1703
  //#endregion
328
1704
  //#region src/cli.ts
@@ -339,55 +1715,514 @@ const { values, positionals } = parseArgs({
339
1715
  type: "string",
340
1716
  short: "o"
341
1717
  },
1718
+ outDir: {
1719
+ type: "string",
1720
+ short: "d"
1721
+ },
1722
+ runtimePath: {
1723
+ type: "string",
1724
+ short: "r"
1725
+ },
1726
+ dynamic: {
1727
+ type: "boolean",
1728
+ short: "D"
1729
+ },
1730
+ interactive: {
1731
+ type: "boolean",
1732
+ short: "i"
1733
+ },
342
1734
  help: {
343
1735
  type: "boolean",
344
1736
  short: "h"
1737
+ },
1738
+ version: {
1739
+ type: "boolean",
1740
+ short: "v"
345
1741
  }
346
1742
  },
347
1743
  allowPositionals: true
348
1744
  });
1745
+ const VERSION = "3.0.0";
1746
+ if (values.version) {
1747
+ console.log(VERSION);
1748
+ process.exit(0);
1749
+ }
349
1750
  if (values.help || positionals.length === 0) {
350
1751
  console.log(`
351
- Cap'n Proto TypeScript CLI
1752
+ Cap'n Proto TypeScript Code Generator v3
352
1753
 
353
- Usage:
354
- capnp gen <schema.capnp> [options] Generate TypeScript from schema
355
- capnp --help Show this help
1754
+ Usage: capnp-ts-codegen <schema.capnp> [options]
356
1755
 
357
1756
  Options:
358
- -o, --output Output file (default: stdout)
359
- -h, --help Show this help
1757
+ -o, --output Output file (default: stdout for single file)
1758
+ -d, --outDir Output directory for multiple files
1759
+ -r, --runtimePath Runtime library import path (default: @naeemo/capnp)
1760
+ -D, --dynamic Generate dynamic schema loading code
1761
+ -i, --interactive Start interactive schema query tool
1762
+ -h, --help Show this help
1763
+ -v, --version Show version
360
1764
 
361
1765
  Examples:
362
- npx @naeemo/capnp gen schema.capnp -o types.ts
363
- capnp gen schema.capnp > types.ts
1766
+ capnp-ts-codegen schema.capnp -o schema.ts
1767
+ capnp-ts-codegen schema.capnp -d ./generated
1768
+ capnp-ts-codegen schema.capnp -o schema.ts -r ../runtime
1769
+ capnp-ts-codegen schema.capnp -D -o schema-dynamic.ts
1770
+ capnp-ts-codegen schema.capnp -i
1771
+
1772
+ Features:
1773
+ - Struct with all primitive types
1774
+ - Enum
1775
+ - List<T>
1776
+ - Text, Data
1777
+ - Nested struct references
1778
+ - Union (discriminant handling)
1779
+ - Group
1780
+ - Default values (XOR encoding)
1781
+ - Multi-segment messages
1782
+ - Interface (RPC client/server generation)
1783
+ - Dynamic schema loading (Phase 7)
1784
+
1785
+ Not yet supported:
1786
+ - Const
1787
+ - Advanced RPC features (Level 2-4)
364
1788
  `);
365
1789
  process.exit(0);
366
1790
  }
367
- const command = positionals[0];
368
- if (command !== "gen") {
369
- console.error(`Unknown command: ${command}`);
370
- console.error("Run \"capnp --help\" for usage");
1791
+ const inputFile = positionals[0];
1792
+ if (!existsSync(inputFile)) {
1793
+ console.error(`Error: File not found: ${inputFile}`);
371
1794
  process.exit(1);
372
1795
  }
373
- const inputFile = positionals[1];
374
- if (!inputFile) {
375
- console.error("Error: Missing input file");
376
- console.error("Usage: capnp gen <schema.capnp>");
377
- process.exit(1);
1796
+ function checkCapnpTool() {
1797
+ try {
1798
+ execSync("capnp --version", { stdio: "ignore" });
1799
+ return true;
1800
+ } catch {
1801
+ return false;
1802
+ }
378
1803
  }
379
- const outputFile = values.output;
380
1804
  async function main() {
381
- const code = generateCode(parseSchemaV2(readFileSync(inputFile, "utf-8")));
382
- if (outputFile) {
383
- writeFileSync(outputFile, code);
384
- console.error(`Generated: ${outputFile}`);
385
- } else console.log(code);
386
- }
387
- main().catch((err) => {
388
- console.error("Error:", err.message);
389
- process.exit(1);
390
- });
1805
+ if (values.interactive) {
1806
+ await runInteractiveMode(inputFile);
1807
+ return;
1808
+ }
1809
+ if (!checkCapnpTool()) {
1810
+ console.error("Error: capnp tool not found. Please install Cap'n Proto.");
1811
+ console.error(" macOS: brew install capnp");
1812
+ console.error(" Ubuntu/Debian: apt-get install capnproto");
1813
+ console.error(" Other: https://capnproto.org/install.html");
1814
+ process.exit(1);
1815
+ }
1816
+ const tmpDir = mkdtempSync(join(tmpdir(), "capnp-ts-"));
1817
+ const binFile = join(tmpDir, "schema.bin");
1818
+ try {
1819
+ console.error(`Compiling ${inputFile}...`);
1820
+ const inputDir = dirname(inputFile);
1821
+ execSync(`capnp compile -o- "${inputFile}" > "${binFile}"`, {
1822
+ cwd: inputDir,
1823
+ stdio: [
1824
+ "ignore",
1825
+ "ignore",
1826
+ "pipe"
1827
+ ]
1828
+ });
1829
+ console.error("Reading binary schema...");
1830
+ const buffer = readFileSync(binFile);
1831
+ const arrayBuffer = new Uint8Array(buffer.byteLength);
1832
+ arrayBuffer.set(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength));
1833
+ if (values.dynamic) {
1834
+ console.error("Generating dynamic schema loading code...");
1835
+ const dynamicCode = generateDynamicLoadingCode(inputFile, arrayBuffer.buffer);
1836
+ if (values.output) {
1837
+ writeFileSync(values.output, dynamicCode);
1838
+ console.error(`Dynamic loading code written to ${values.output}`);
1839
+ } else console.log(dynamicCode);
1840
+ return;
1841
+ }
1842
+ console.error("Generating TypeScript code...");
1843
+ const files = generateFromRequest(CodeGeneratorRequestReader.fromBuffer(arrayBuffer.buffer), { runtimeImportPath: values.runtimePath || "@naeemo/capnp" });
1844
+ if (values.outDir) {
1845
+ mkdirSync(values.outDir, { recursive: true });
1846
+ for (const [filename, code] of files) {
1847
+ const outPath = join(values.outDir, filename);
1848
+ mkdirSync(dirname(outPath), { recursive: true });
1849
+ writeFileSync(outPath, code);
1850
+ console.error(`Generated: ${outPath}`);
1851
+ }
1852
+ } else if (values.output) {
1853
+ const firstFile = files.values().next().value;
1854
+ if (firstFile) {
1855
+ writeFileSync(values.output, firstFile);
1856
+ console.error(`Output written to ${values.output}`);
1857
+ } else {
1858
+ console.error("Error: No files generated");
1859
+ process.exit(1);
1860
+ }
1861
+ } else {
1862
+ const firstFile = files.values().next().value;
1863
+ if (firstFile) console.log(firstFile);
1864
+ else {
1865
+ console.error("Error: No files generated");
1866
+ process.exit(1);
1867
+ }
1868
+ }
1869
+ } catch (err) {
1870
+ console.error("Error:", err.message);
1871
+ if (err.stderr) console.error(err.stderr.toString());
1872
+ process.exit(1);
1873
+ } finally {
1874
+ rmSync(tmpDir, {
1875
+ recursive: true,
1876
+ force: true
1877
+ });
1878
+ }
1879
+ }
1880
+ main();
1881
+ /**
1882
+ * Generate dynamic schema loading code for the given schema file
1883
+ */
1884
+ function generateDynamicLoadingCode(inputFile, buffer) {
1885
+ const nodes = CodeGeneratorRequestReader.fromBuffer(buffer).nodes;
1886
+ const runtimePath = values.runtimePath || "@naeemo/capnp";
1887
+ const schemaName = basename(inputFile, ".capnp");
1888
+ const structTypes = [];
1889
+ const interfaceTypes = [];
1890
+ for (const node of nodes) {
1891
+ const id = node.id;
1892
+ const displayName = node.displayName;
1893
+ const shortName = displayName.split(".").pop() || displayName;
1894
+ if (node.isStruct) structTypes.push({
1895
+ id: `0x${id.toString(16)}n`,
1896
+ name: shortName,
1897
+ displayName
1898
+ });
1899
+ else if (node.isInterface) interfaceTypes.push({
1900
+ id: `0x${id.toString(16)}n`,
1901
+ name: shortName,
1902
+ displayName
1903
+ });
1904
+ }
1905
+ return `/**
1906
+ * Dynamic Schema Loading for ${schemaName}.capnp
1907
+ *
1908
+ * This file provides runtime schema loading capabilities for ${schemaName}.capnp
1909
+ * Generated by capnp-ts-codegen --dynamic
1910
+ *
1911
+ * Usage:
1912
+ * import { load${toPascalCase(schemaName)}Schema, ${structTypes.map((t) => t.name).join(", ")} } from './${schemaName}-dynamic';
1913
+ *
1914
+ * // Load schema from remote connection
1915
+ * const schema = await load${toPascalCase(schemaName)}Schema(connection);
1916
+ *
1917
+ * // Use dynamic reader
1918
+ * const reader = createDynamicReader(schema.Person, buffer);
1919
+ * console.log(reader.get('name'));
1920
+ */
1921
+
1922
+ import {
1923
+ RpcConnection,
1924
+ createDynamicReader,
1925
+ createDynamicWriter,
1926
+ dumpDynamicReader,
1927
+ type SchemaNode,
1928
+ type SchemaRegistry,
1929
+ } from '${runtimePath}';
1930
+
1931
+ // =============================================================================
1932
+ // Type IDs
1933
+ // =============================================================================
1934
+
1935
+ ${structTypes.map((t) => `/** Type ID for ${t.displayName} */\nexport const ${t.name}TypeId = ${t.id};`).join("\n")}
1936
+
1937
+ ${interfaceTypes.map((t) => `/** Interface ID for ${t.displayName} */\nexport const ${t.name}InterfaceId = ${t.id};`).join("\n")}
1938
+
1939
+ // =============================================================================
1940
+ // Schema Cache
1941
+ // =============================================================================
1942
+
1943
+ let cachedSchemaRegistry: SchemaRegistry | null = null;
1944
+
1945
+ // =============================================================================
1946
+ // Schema Loading Functions
1947
+ // =============================================================================
1948
+
1949
+ /**
1950
+ * Load all schemas for ${schemaName}.capnp from a remote connection.
1951
+ * This fetches schema information dynamically and caches it for reuse.
1952
+ *
1953
+ * @param connection - The RPC connection to fetch schemas from
1954
+ * @returns A registry containing all loaded schemas
1955
+ */
1956
+ export async function load${toPascalCase(schemaName)}Schema(connection: RpcConnection): Promise<SchemaRegistry> {
1957
+ if (cachedSchemaRegistry) {
1958
+ return cachedSchemaRegistry;
1959
+ }
1960
+
1961
+ // Fetch all schemas
1962
+ const typeIds = [
1963
+ ${structTypes.map((t) => `${t.name}TypeId`).join(",\n ")}
1964
+ ];
1965
+
1966
+ for (const typeId of typeIds) {
1967
+ try {
1968
+ await connection.getDynamicSchema(typeId);
1969
+ } catch (err) {
1970
+ console.warn(\`Failed to load schema for type \${typeId}:\`, err);
1971
+ }
1972
+ }
1973
+
1974
+ cachedSchemaRegistry = connection.getSchemaRegistry();
1975
+ return cachedSchemaRegistry;
1976
+ }
1977
+
1978
+ /**
1979
+ * Get a specific schema node by type ID.
1980
+ * Loads from remote if not already cached.
1981
+ *
1982
+ * @param connection - The RPC connection
1983
+ * @param typeId - The type ID to fetch
1984
+ * @returns The schema node
1985
+ */
1986
+ export async function getSchema(connection: RpcConnection, typeId: bigint): Promise<SchemaNode> {
1987
+ return connection.getDynamicSchema(typeId);
1988
+ }
1989
+
1990
+ /**
1991
+ * Clear the schema cache.
1992
+ * Call this if you need to re-fetch schemas from the remote server.
1993
+ */
1994
+ export function clearSchemaCache(): void {
1995
+ cachedSchemaRegistry = null;
1996
+ }
1997
+
1998
+ // =============================================================================
1999
+ // Dynamic Reader Helpers
2000
+ // =============================================================================
2001
+
2002
+ ${structTypes.map((t) => `
2003
+ /**
2004
+ * Create a dynamic reader for ${t.name}
2005
+ *
2006
+ * @param buffer - The Cap'n Proto message buffer
2007
+ * @param registry - Optional schema registry (will use cached if available)
2008
+ * @returns A DynamicReader for the message
2009
+ */
2010
+ export function create${toPascalCase(t.name)}Reader(
2011
+ buffer: ArrayBuffer | Uint8Array,
2012
+ registry?: SchemaRegistry
2013
+ ): DynamicReader {
2014
+ const reg = registry || cachedSchemaRegistry;
2015
+ if (!reg) {
2016
+ throw new Error('Schema registry not loaded. Call load${toPascalCase(schemaName)}Schema first.');
2017
+ }
2018
+
2019
+ const schema = reg.getNode(${t.name}TypeId);
2020
+ if (!schema) {
2021
+ throw new Error('Schema for ${t.name} not found in registry');
2022
+ }
2023
+
2024
+ return createDynamicReader(schema, buffer);
2025
+ }
2026
+ `).join("\n")}
2027
+
2028
+ // =============================================================================
2029
+ // Utility Functions
2030
+ // =============================================================================
2031
+
2032
+ /**
2033
+ * Dump all fields from a dynamic reader for debugging
2034
+ */
2035
+ export { dumpDynamicReader };
2036
+
2037
+ /**
2038
+ * List all available types in this schema
2039
+ */
2040
+ export function listTypes(): Array<{ name: string; typeId: string; kind: 'struct' | 'interface' }> {
2041
+ return [
2042
+ ${structTypes.map((t) => `{ name: '${t.name}', typeId: '${t.id}', kind: 'struct' as const }`).join(",\n ")},
2043
+ ${interfaceTypes.map((t) => `{ name: '${t.name}', typeId: '${t.id}', kind: 'interface' as const }`).join(",\n ")},
2044
+ ];
2045
+ }
2046
+ `;
2047
+ }
2048
+ /**
2049
+ * Run interactive schema query tool
2050
+ */
2051
+ async function runInteractiveMode(inputFile) {
2052
+ if (!checkCapnpTool()) {
2053
+ console.error("Error: capnp tool not found. Please install Cap'n Proto.");
2054
+ process.exit(1);
2055
+ }
2056
+ const tmpDir = mkdtempSync(join(tmpdir(), "capnp-ts-"));
2057
+ const binFile = join(tmpDir, "schema.bin");
2058
+ try {
2059
+ console.log(`\n🔍 Loading schema: ${inputFile}...\n`);
2060
+ const inputDir = dirname(inputFile);
2061
+ execSync(`capnp compile -o- "${inputFile}" > "${binFile}"`, {
2062
+ cwd: inputDir,
2063
+ stdio: [
2064
+ "ignore",
2065
+ "ignore",
2066
+ "pipe"
2067
+ ]
2068
+ });
2069
+ const buffer = readFileSync(binFile);
2070
+ const arrayBuffer = new Uint8Array(buffer.byteLength);
2071
+ arrayBuffer.set(new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength));
2072
+ const nodes = CodeGeneratorRequestReader.fromBuffer(arrayBuffer.buffer).nodes;
2073
+ const typeIndex = /* @__PURE__ */ new Map();
2074
+ for (const node of nodes) {
2075
+ const id = node.id;
2076
+ const displayName = node.displayName;
2077
+ const shortName = displayName.split(".").pop() || displayName;
2078
+ let kind = "unknown";
2079
+ if (node.isStruct) kind = "struct";
2080
+ else if (node.isInterface) kind = "interface";
2081
+ else if (node.isEnum) kind = "enum";
2082
+ else if (node.isConst) kind = "const";
2083
+ typeIndex.set(shortName, {
2084
+ id,
2085
+ displayName,
2086
+ kind,
2087
+ node
2088
+ });
2089
+ typeIndex.set(displayName, {
2090
+ id,
2091
+ displayName,
2092
+ kind,
2093
+ node
2094
+ });
2095
+ typeIndex.set(id.toString(16), {
2096
+ id,
2097
+ displayName,
2098
+ kind,
2099
+ node
2100
+ });
2101
+ }
2102
+ console.log("📋 Available types:");
2103
+ console.log("─".repeat(60));
2104
+ const structs = [];
2105
+ const interfaces = [];
2106
+ const enums = [];
2107
+ for (const [name, info] of typeIndex) {
2108
+ if (name.includes(".")) continue;
2109
+ if (info.kind === "struct") structs.push(name);
2110
+ else if (info.kind === "interface") interfaces.push(name);
2111
+ else if (info.kind === "enum") enums.push(name);
2112
+ }
2113
+ if (structs.length > 0) {
2114
+ console.log("\n🏗️ Structs:");
2115
+ for (const name of structs.sort()) {
2116
+ const info = typeIndex.get(name);
2117
+ console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2118
+ }
2119
+ }
2120
+ if (interfaces.length > 0) {
2121
+ console.log("\n🔌 Interfaces:");
2122
+ for (const name of interfaces.sort()) {
2123
+ const info = typeIndex.get(name);
2124
+ console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2125
+ }
2126
+ }
2127
+ if (enums.length > 0) {
2128
+ console.log("\n📊 Enums:");
2129
+ for (const name of enums.sort()) {
2130
+ const info = typeIndex.get(name);
2131
+ console.log(` ${name.padEnd(30)} (0x${info.id.toString(16)})`);
2132
+ }
2133
+ }
2134
+ console.log(`\n${"─".repeat(60)}`);
2135
+ console.log("💡 Commands:");
2136
+ console.log(" inspect <type> - Show detailed information about a type");
2137
+ console.log(" ids - List all type IDs");
2138
+ console.log(" export - Export schema info as JSON");
2139
+ console.log(" quit - Exit interactive mode");
2140
+ console.log("");
2141
+ const stdin = process.stdin;
2142
+ const stdout = process.stdout;
2143
+ stdin.setEncoding("utf8");
2144
+ stdin.resume();
2145
+ stdout.write("> ");
2146
+ stdin.on("data", (data) => {
2147
+ const line = data.trim();
2148
+ const parts = line.split(/\s+/);
2149
+ const command = parts[0];
2150
+ const arg = parts[1];
2151
+ switch (command) {
2152
+ case "quit":
2153
+ case "exit":
2154
+ case "q":
2155
+ console.log("👋 Goodbye!");
2156
+ process.exit(0);
2157
+ break;
2158
+ case "inspect":
2159
+ if (!arg) console.log("❌ Usage: inspect <type-name>");
2160
+ else {
2161
+ const info = typeIndex.get(arg);
2162
+ if (info) {
2163
+ console.log(`\n🔍 ${info.displayName}`);
2164
+ console.log(` ${"─".repeat(50)}`);
2165
+ console.log(` Type ID: 0x${info.id.toString(16)}`);
2166
+ console.log(` Kind: ${info.kind}`);
2167
+ console.log("");
2168
+ } else console.log(`❌ Type "${arg}" not found`);
2169
+ }
2170
+ break;
2171
+ case "ids":
2172
+ console.log("\n📋 All Type IDs:");
2173
+ console.log(` ${"─".repeat(50)}`);
2174
+ for (const [name, info] of typeIndex) {
2175
+ if (name.includes(".")) continue;
2176
+ console.log(` 0x${info.id.toString(16).padStart(16, "0")} ${info.displayName}`);
2177
+ }
2178
+ console.log("");
2179
+ break;
2180
+ case "export": {
2181
+ const exportData = {
2182
+ sourceFile: inputFile,
2183
+ types: Array.from(typeIndex.entries()).filter(([name]) => !name.includes(".")).map(([name, info]) => ({
2184
+ name,
2185
+ displayName: info.displayName,
2186
+ typeId: `0x${info.id.toString(16)}`,
2187
+ kind: info.kind
2188
+ }))
2189
+ };
2190
+ console.log(JSON.stringify(exportData, null, 2));
2191
+ break;
2192
+ }
2193
+ case "help":
2194
+ case "h":
2195
+ console.log("\n💡 Commands:");
2196
+ console.log(" inspect <type> - Show detailed information about a type");
2197
+ console.log(" ids - List all type IDs");
2198
+ console.log(" export - Export schema info as JSON");
2199
+ console.log(" quit - Exit interactive mode");
2200
+ console.log("");
2201
+ break;
2202
+ default: if (line) {
2203
+ console.log(`❌ Unknown command: ${command}`);
2204
+ console.log(" Type \"help\" for available commands");
2205
+ }
2206
+ }
2207
+ stdout.write("> ");
2208
+ });
2209
+ await new Promise(() => {});
2210
+ } catch (err) {
2211
+ console.error("Error:", err.message);
2212
+ process.exit(1);
2213
+ } finally {
2214
+ rmSync(tmpDir, {
2215
+ recursive: true,
2216
+ force: true
2217
+ });
2218
+ }
2219
+ }
2220
+ /**
2221
+ * Convert string to PascalCase
2222
+ */
2223
+ function toPascalCase(str) {
2224
+ return str.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join("");
2225
+ }
391
2226
 
392
2227
  //#endregion
393
2228
  export { };