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