@aztec/bb.js 0.0.1-commit.d3ec352c → 0.0.1-commit.e310a4c8

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.
Files changed (187) hide show
  1. package/build/amd64-linux/bb +0 -0
  2. package/build/amd64-linux/nodejs_module.node +0 -0
  3. package/build/amd64-macos/bb +0 -0
  4. package/build/amd64-macos/nodejs_module.node +0 -0
  5. package/build/arm64-linux/bb +0 -0
  6. package/build/arm64-linux/nodejs_module.node +0 -0
  7. package/build/arm64-macos/bb +0 -0
  8. package/build/arm64-macos/nodejs_module.node +0 -0
  9. package/dest/browser/barretenberg/backend.d.ts +49 -17
  10. package/dest/browser/barretenberg/backend.d.ts.map +1 -1
  11. package/dest/browser/barretenberg/backend.js +109 -9
  12. package/dest/browser/barretenberg/index.d.ts +2 -2
  13. package/dest/browser/barretenberg/index.d.ts.map +1 -1
  14. package/dest/browser/barretenberg/index.js +2 -2
  15. package/dest/browser/barretenberg_wasm/barretenberg_wasm_main/index.js +1 -1
  16. package/dest/browser/barretenberg_wasm/fetch_code/browser/barretenberg-threads.js +1 -1
  17. package/dest/browser/barretenberg_wasm/fetch_code/browser/barretenberg.js +1 -1
  18. package/dest/browser/bb_backends/index.d.ts +3 -1
  19. package/dest/browser/bb_backends/index.d.ts.map +1 -1
  20. package/dest/browser/cbind/generate.d.ts +5 -2
  21. package/dest/browser/cbind/generate.d.ts.map +1 -1
  22. package/dest/browser/cbind/generate.js +47 -25
  23. package/dest/browser/cbind/generated/api_types.d.ts +765 -1672
  24. package/dest/browser/cbind/generated/api_types.d.ts.map +1 -1
  25. package/dest/browser/cbind/generated/api_types.js +1453 -1525
  26. package/dest/browser/cbind/generated/async.d.ts +3 -5
  27. package/dest/browser/cbind/generated/async.d.ts.map +1 -1
  28. package/dest/browser/cbind/generated/async.js +13 -33
  29. package/dest/browser/cbind/generated/sync.d.ts +3 -5
  30. package/dest/browser/cbind/generated/sync.d.ts.map +1 -1
  31. package/dest/browser/cbind/generated/sync.js +13 -31
  32. package/dest/browser/cbind/naming.d.ts +16 -0
  33. package/dest/browser/cbind/naming.d.ts.map +1 -0
  34. package/dest/browser/cbind/naming.js +24 -0
  35. package/dest/browser/cbind/rust_codegen.d.ts +26 -0
  36. package/dest/browser/cbind/rust_codegen.d.ts.map +1 -0
  37. package/dest/browser/cbind/rust_codegen.js +461 -0
  38. package/dest/browser/cbind/schema_visitor.d.ts +47 -0
  39. package/dest/browser/cbind/schema_visitor.d.ts.map +1 -0
  40. package/dest/browser/cbind/schema_visitor.js +158 -0
  41. package/dest/browser/cbind/typescript_codegen.d.ts +30 -0
  42. package/dest/browser/cbind/typescript_codegen.d.ts.map +1 -0
  43. package/dest/browser/cbind/typescript_codegen.js +365 -0
  44. package/dest/browser/index.d.ts +2 -2
  45. package/dest/browser/index.d.ts.map +1 -1
  46. package/dest/browser/index.js +2 -2
  47. package/dest/node/barretenberg/backend.d.ts +49 -17
  48. package/dest/node/barretenberg/backend.d.ts.map +1 -1
  49. package/dest/node/barretenberg/backend.js +109 -9
  50. package/dest/node/barretenberg/backend.test.d.ts +2 -0
  51. package/dest/node/barretenberg/backend.test.d.ts.map +1 -0
  52. package/dest/node/barretenberg/backend.test.js +103 -0
  53. package/dest/node/barretenberg/index.d.ts +2 -2
  54. package/dest/node/barretenberg/index.d.ts.map +1 -1
  55. package/dest/node/barretenberg/index.js +2 -2
  56. package/dest/node/barretenberg_wasm/barretenberg-threads.wasm.gz +0 -0
  57. package/dest/node/barretenberg_wasm/barretenberg_wasm_main/index.js +1 -1
  58. package/dest/node/bb_backends/index.d.ts +3 -1
  59. package/dest/node/bb_backends/index.d.ts.map +1 -1
  60. package/dest/node/bb_backends/node/index.d.ts +1 -1
  61. package/dest/node/bb_backends/node/index.d.ts.map +1 -1
  62. package/dest/node/bb_backends/node/index.js +5 -5
  63. package/dest/node/bb_backends/node/native_shm.d.ts +3 -2
  64. package/dest/node/bb_backends/node/native_shm.d.ts.map +1 -1
  65. package/dest/node/bb_backends/node/native_shm.js +40 -21
  66. package/dest/node/bb_backends/node/native_shm_async.d.ts +2 -2
  67. package/dest/node/bb_backends/node/native_shm_async.d.ts.map +1 -1
  68. package/dest/node/bb_backends/node/native_shm_async.js +17 -21
  69. package/dest/node/bb_backends/node/native_socket.d.ts +1 -1
  70. package/dest/node/bb_backends/node/native_socket.d.ts.map +1 -1
  71. package/dest/node/bb_backends/node/native_socket.js +7 -5
  72. package/dest/node/bb_backends/node/platform.d.ts +1 -1
  73. package/dest/node/bb_backends/node/platform.d.ts.map +1 -1
  74. package/dest/node/bb_backends/node/platform.js +7 -2
  75. package/dest/node/cbind/generate.d.ts +5 -2
  76. package/dest/node/cbind/generate.d.ts.map +1 -1
  77. package/dest/node/cbind/generate.js +47 -25
  78. package/dest/node/cbind/generated/api_types.d.ts +765 -1672
  79. package/dest/node/cbind/generated/api_types.d.ts.map +1 -1
  80. package/dest/node/cbind/generated/api_types.js +1453 -1525
  81. package/dest/node/cbind/generated/async.d.ts +3 -5
  82. package/dest/node/cbind/generated/async.d.ts.map +1 -1
  83. package/dest/node/cbind/generated/async.js +13 -33
  84. package/dest/node/cbind/generated/sync.d.ts +3 -5
  85. package/dest/node/cbind/generated/sync.d.ts.map +1 -1
  86. package/dest/node/cbind/generated/sync.js +13 -31
  87. package/dest/node/cbind/naming.d.ts +16 -0
  88. package/dest/node/cbind/naming.d.ts.map +1 -0
  89. package/dest/node/cbind/naming.js +24 -0
  90. package/dest/node/cbind/rust_codegen.d.ts +26 -0
  91. package/dest/node/cbind/rust_codegen.d.ts.map +1 -0
  92. package/dest/node/cbind/rust_codegen.js +461 -0
  93. package/dest/node/cbind/schema_visitor.d.ts +47 -0
  94. package/dest/node/cbind/schema_visitor.d.ts.map +1 -0
  95. package/dest/node/cbind/schema_visitor.js +158 -0
  96. package/dest/node/cbind/typescript_codegen.d.ts +30 -0
  97. package/dest/node/cbind/typescript_codegen.d.ts.map +1 -0
  98. package/dest/node/cbind/typescript_codegen.js +365 -0
  99. package/dest/node/index.d.ts +2 -2
  100. package/dest/node/index.d.ts.map +1 -1
  101. package/dest/node/index.js +2 -2
  102. package/dest/node-cjs/barretenberg/backend.d.ts +49 -17
  103. package/dest/node-cjs/barretenberg/backend.d.ts.map +1 -1
  104. package/dest/node-cjs/barretenberg/backend.js +111 -9
  105. package/dest/node-cjs/barretenberg/backend.test.d.ts +2 -0
  106. package/dest/node-cjs/barretenberg/backend.test.d.ts.map +1 -0
  107. package/dest/node-cjs/barretenberg/backend.test.js +105 -0
  108. package/dest/node-cjs/barretenberg/index.d.ts +2 -2
  109. package/dest/node-cjs/barretenberg/index.d.ts.map +1 -1
  110. package/dest/node-cjs/barretenberg/index.js +4 -2
  111. package/dest/node-cjs/barretenberg_wasm/barretenberg-threads.wasm.gz +0 -0
  112. package/dest/node-cjs/barretenberg_wasm/barretenberg_wasm_main/index.js +1 -1
  113. package/dest/node-cjs/bb_backends/index.d.ts +3 -1
  114. package/dest/node-cjs/bb_backends/index.d.ts.map +1 -1
  115. package/dest/node-cjs/bb_backends/node/index.d.ts +1 -1
  116. package/dest/node-cjs/bb_backends/node/index.d.ts.map +1 -1
  117. package/dest/node-cjs/bb_backends/node/index.js +5 -5
  118. package/dest/node-cjs/bb_backends/node/native_shm.d.ts +3 -2
  119. package/dest/node-cjs/bb_backends/node/native_shm.d.ts.map +1 -1
  120. package/dest/node-cjs/bb_backends/node/native_shm.js +39 -20
  121. package/dest/node-cjs/bb_backends/node/native_shm_async.d.ts +2 -2
  122. package/dest/node-cjs/bb_backends/node/native_shm_async.d.ts.map +1 -1
  123. package/dest/node-cjs/bb_backends/node/native_shm_async.js +17 -21
  124. package/dest/node-cjs/bb_backends/node/native_socket.d.ts +1 -1
  125. package/dest/node-cjs/bb_backends/node/native_socket.d.ts.map +1 -1
  126. package/dest/node-cjs/bb_backends/node/native_socket.js +7 -5
  127. package/dest/node-cjs/bb_backends/node/platform.d.ts +1 -1
  128. package/dest/node-cjs/bb_backends/node/platform.d.ts.map +1 -1
  129. package/dest/node-cjs/bb_backends/node/platform.js +7 -2
  130. package/dest/node-cjs/cbind/generate.d.ts +5 -2
  131. package/dest/node-cjs/cbind/generate.d.ts.map +1 -1
  132. package/dest/node-cjs/cbind/generate.js +47 -25
  133. package/dest/node-cjs/cbind/generated/api_types.d.ts +765 -1672
  134. package/dest/node-cjs/cbind/generated/api_types.d.ts.map +1 -1
  135. package/dest/node-cjs/cbind/generated/api_types.js +1662 -1742
  136. package/dest/node-cjs/cbind/generated/async.d.ts +3 -5
  137. package/dest/node-cjs/cbind/generated/async.d.ts.map +1 -1
  138. package/dest/node-cjs/cbind/generated/async.js +12 -32
  139. package/dest/node-cjs/cbind/generated/sync.d.ts +3 -5
  140. package/dest/node-cjs/cbind/generated/sync.d.ts.map +1 -1
  141. package/dest/node-cjs/cbind/generated/sync.js +12 -30
  142. package/dest/node-cjs/cbind/naming.d.ts +16 -0
  143. package/dest/node-cjs/cbind/naming.d.ts.map +1 -0
  144. package/dest/node-cjs/cbind/naming.js +28 -0
  145. package/dest/node-cjs/cbind/rust_codegen.d.ts +26 -0
  146. package/dest/node-cjs/cbind/rust_codegen.d.ts.map +1 -0
  147. package/dest/node-cjs/cbind/rust_codegen.js +465 -0
  148. package/dest/node-cjs/cbind/schema_visitor.d.ts +47 -0
  149. package/dest/node-cjs/cbind/schema_visitor.d.ts.map +1 -0
  150. package/dest/node-cjs/cbind/schema_visitor.js +162 -0
  151. package/dest/node-cjs/cbind/typescript_codegen.d.ts +30 -0
  152. package/dest/node-cjs/cbind/typescript_codegen.d.ts.map +1 -0
  153. package/dest/node-cjs/cbind/typescript_codegen.js +369 -0
  154. package/dest/node-cjs/index.d.ts +2 -2
  155. package/dest/node-cjs/index.d.ts.map +1 -1
  156. package/dest/node-cjs/index.js +4 -2
  157. package/package.json +1 -1
  158. package/src/barretenberg/backend.test.ts +122 -0
  159. package/src/barretenberg/backend.ts +149 -23
  160. package/src/barretenberg/index.ts +9 -1
  161. package/src/barretenberg_wasm/barretenberg_wasm_main/index.ts +1 -1
  162. package/src/bb_backends/index.ts +3 -0
  163. package/src/bb_backends/node/index.ts +9 -4
  164. package/src/bb_backends/node/native_shm.ts +38 -19
  165. package/src/bb_backends/node/native_shm_async.ts +15 -19
  166. package/src/bb_backends/node/native_socket.ts +7 -5
  167. package/src/bb_backends/node/platform.ts +6 -1
  168. package/src/cbind/generate.ts +51 -32
  169. package/src/cbind/naming.ts +27 -0
  170. package/src/cbind/rust_codegen.ts +504 -0
  171. package/src/cbind/schema_visitor.ts +219 -0
  172. package/src/cbind/typescript_codegen.ts +419 -0
  173. package/src/index.ts +4 -0
  174. package/dest/browser/cbind/schema_compiler.d.ts +0 -68
  175. package/dest/browser/cbind/schema_compiler.d.ts.map +0 -1
  176. package/dest/browser/cbind/schema_compiler.js +0 -600
  177. package/dest/node/cbind/schema_compiler.d.ts +0 -68
  178. package/dest/node/cbind/schema_compiler.d.ts.map +0 -1
  179. package/dest/node/cbind/schema_compiler.js +0 -600
  180. package/dest/node-cjs/cbind/schema_compiler.d.ts +0 -68
  181. package/dest/node-cjs/cbind/schema_compiler.d.ts.map +0 -1
  182. package/dest/node-cjs/cbind/schema_compiler.js +0 -607
  183. package/src/cbind/generated/api_types.ts +0 -4241
  184. package/src/cbind/generated/async.ts +0 -717
  185. package/src/cbind/generated/curve_constants.ts +0 -53
  186. package/src/cbind/generated/sync.ts +0 -663
  187. package/src/cbind/schema_compiler.ts +0 -745
@@ -1,745 +0,0 @@
1
- /**
2
- * Unified schema compiler with integrated strategies
3
- */
4
-
5
- // Core type definitions
6
- export type Schema =
7
- | string
8
- | ObjectSchema
9
- | ['tuple', Schema[]]
10
- | ['map', [Schema, Schema]]
11
- | ['optional', [Schema]]
12
- | ['vector', [Schema]]
13
- | ['variant', Schema[]]
14
- | ['named_union', Array<[string, Schema]>]
15
- | ['shared_ptr', [Schema]]
16
- | ['array', [Schema, number]]
17
- | ['alias', [string, string]];
18
-
19
- export type ObjectSchema = { [key: string]: Schema };
20
-
21
- export interface TypeInfo {
22
- typeName: string;
23
- msgpackTypeName?: string;
24
- declaration?: string;
25
- toMethod?: string;
26
- fromMethod?: string;
27
- }
28
-
29
- export interface FunctionMetadata {
30
- name: string;
31
- commandType: string;
32
- responseType: string;
33
- }
34
-
35
- // Compiler configuration
36
- export interface CompilerConfig {
37
- mode: 'types' | 'sync' | 'async';
38
- imports?: string[];
39
- wasmImport?: string;
40
- }
41
-
42
- // Helper functions
43
- function capitalize(s: string): string {
44
- return s.charAt(0).toUpperCase() + s.substring(1);
45
- }
46
-
47
- function camelCase(s: string): string {
48
- return s
49
- .split('_')
50
- .map((part, index) => (index === 0 ? part.charAt(0).toLowerCase() + part.substring(1) : capitalize(part)))
51
- .join('');
52
- }
53
-
54
- function pascalCase(s: string): string {
55
- return s.split('_').map(capitalize).join('');
56
- }
57
-
58
- export class SchemaCompiler {
59
- private typeCache = new Map<string, TypeInfo>();
60
- private functionMetadata: FunctionMetadata[] = [];
61
- // WORKTODO(bbapi): AI slop fixup - redundant with typeCache, remove
62
- private referencedTypes = new Set<string>();
63
-
64
- constructor(private config: CompilerConfig) {}
65
-
66
- /**
67
- * Process API schema and extract function metadata
68
- */
69
- processApiSchema(commandsSchema: Schema, responsesSchema: Schema): void {
70
- // Process types
71
- this.processSchema(commandsSchema);
72
- this.processSchema(responsesSchema);
73
-
74
- // Extract function metadata from named unions
75
- if (
76
- !Array.isArray(commandsSchema) ||
77
- commandsSchema[0] !== 'named_union' ||
78
- !Array.isArray(responsesSchema) ||
79
- responsesSchema[0] !== 'named_union'
80
- ) {
81
- throw new Error('Expected named_union schema format');
82
- }
83
-
84
- const commands = commandsSchema[1] as Array<[string, Schema]>;
85
- const responses = responsesSchema[1] as Array<[string, Schema]>;
86
-
87
- // Filter out ErrorResponse - it's a special error variant, not a command response
88
- const normalResponses = responses.filter(([name]) => name !== 'ErrorResponse');
89
-
90
- if (commands.length !== normalResponses.length) {
91
- throw new Error(`Command count (${commands.length}) does not match response count (${normalResponses.length})`);
92
- }
93
-
94
- for (let i = 0; i < commands.length; i++) {
95
- const [commandName] = commands[i];
96
- const [responseName] = normalResponses[i];
97
-
98
- this.functionMetadata.push({
99
- name: camelCase(commandName),
100
- commandType: pascalCase(commandName),
101
- responseType: pascalCase(responseName),
102
- });
103
- }
104
- }
105
-
106
- /**
107
- * Process a schema and populate type cache
108
- */
109
- processSchema(schema: Schema): TypeInfo {
110
- const key = this.getSchemaKey(schema);
111
- if (this.typeCache.has(key)) {
112
- const ret = this.typeCache.get(key)!;
113
- if (ret.typeName === 'unknown') {
114
- throw new Error(`Recursive schema detected at ${key}, please check your schema for circular references.`);
115
- }
116
- return ret;
117
- }
118
-
119
- this.typeCache.set(key, { typeName: 'unknown', msgpackTypeName: '' });
120
- const typeInfo = this.generateTypeInfo(schema);
121
- this.typeCache.set(key, typeInfo);
122
- return typeInfo;
123
- }
124
-
125
- /**
126
- * Generate the complete output
127
- */
128
- compile(): string {
129
- const parts: string[] = ['// AUTOGENERATED FILE - DO NOT EDIT', ''];
130
-
131
- // Generate imports
132
- parts.push(...this.generateImports());
133
- parts.push('');
134
-
135
- // Generate type declarations only for 'types' mode
136
- if (this.config.mode === 'types') {
137
- const sortedTypes = Array.from(this.typeCache.values())
138
- .filter(t => t.declaration)
139
- .sort((a, b) => a.typeName.localeCompare(b.typeName));
140
-
141
- // Group declarations
142
- const typeAliases = sortedTypes.filter(
143
- t => t.declaration?.startsWith('export type') && !t.declaration?.includes('interface'),
144
- );
145
- const publicInterfaces = sortedTypes.filter(t => t.declaration?.includes('export interface'));
146
- const privateInterfaces = sortedTypes.filter(t => t.declaration?.includes('interface Msgpack'));
147
-
148
- // Add type aliases if needed
149
- if (typeAliases.length > 0) {
150
- parts.push('// Type aliases');
151
- for (const type of typeAliases) {
152
- parts.push(type.declaration!);
153
- }
154
- parts.push('');
155
- }
156
-
157
- // Add tuple helper if needed
158
- if (this.needsTupleHelper()) {
159
- parts.push(
160
- '// Tuple type for fixed-size arrays',
161
- 'type Tuple<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never;',
162
- "type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>;",
163
- '',
164
- '// Helper functions',
165
- 'function mapTuple<T, S, N extends number>(tuple: Tuple<T, N>, fn: (item: T) => S): Tuple<S, N> {',
166
- ' return tuple.map(fn) as Tuple<S, N>;',
167
- '}',
168
- '',
169
- );
170
- }
171
-
172
- // Add public interfaces
173
- if (publicInterfaces.length > 0) {
174
- parts.push('// Public interfaces (exported)');
175
- for (const type of publicInterfaces) {
176
- parts.push(type.declaration!, '');
177
- }
178
- }
179
-
180
- // Add private interfaces
181
- if (privateInterfaces.length > 0) {
182
- parts.push('// Private Msgpack interfaces (not exported)');
183
- for (const type of privateInterfaces) {
184
- parts.push(type.declaration!, '');
185
- }
186
- }
187
-
188
- // Add conversion functions (only for api_types.ts)
189
- const conversions = sortedTypes.filter(t => t.toMethod || t.fromMethod);
190
- if (conversions.length > 0) {
191
- parts.push('// Conversion functions (exported)');
192
- for (const type of conversions) {
193
- if (type.toMethod) {
194
- parts.push('export ' + type.toMethod, '');
195
- }
196
- if (type.fromMethod) {
197
- parts.push('export ' + type.fromMethod, '');
198
- }
199
- }
200
- }
201
-
202
- // Add BbApiBase interface
203
- if (this.functionMetadata.length > 0) {
204
- parts.push('', '// Base API interface');
205
- parts.push(this.generateBbApiBaseInterface());
206
- }
207
- }
208
-
209
- // Add API class for non-types modes
210
- if (this.config.mode !== 'types' && this.functionMetadata.length > 0) {
211
- parts.push(this.generateApiClass());
212
- }
213
-
214
- return parts.join('\n') + '\n';
215
- }
216
-
217
- private getSchemaKey(schema: Schema): string {
218
- if (typeof schema === 'string') return schema;
219
- if (Array.isArray(schema)) return JSON.stringify(schema);
220
- if (typeof schema === 'object') return (schema as any).__typename || JSON.stringify(schema);
221
- return String(schema);
222
- }
223
-
224
- private needsTupleHelper(): boolean {
225
- return Array.from(this.typeCache.values()).some(t => t.typeName.includes('Tuple<'));
226
- }
227
-
228
- private trackTypeUsage(typeName: string): void {
229
- // Only track for API modes
230
- if (this.config.mode === 'types') return;
231
-
232
- // Extract base types from complex types
233
- const baseTypes = this.extractBaseTypes(typeName);
234
-
235
- for (const type of baseTypes) {
236
- // Skip built-in types
237
- if (['string', 'number', 'boolean', 'Uint8Array'].includes(type)) {
238
- continue;
239
- }
240
-
241
- this.referencedTypes.add(type);
242
- }
243
- }
244
-
245
- private extractBaseTypes(typeName: string): string[] {
246
- const types: string[] = [];
247
-
248
- // Handle arrays
249
- const arrayMatch = typeName.match(/^(.+)\[\]$/);
250
- if (arrayMatch) {
251
- types.push(...this.extractBaseTypes(arrayMatch[1]));
252
- return types;
253
- }
254
-
255
- // Handle Tuple
256
- const tupleMatch = typeName.match(/^Tuple<(.+),\s*\d+>$/);
257
- if (tupleMatch) {
258
- types.push(...this.extractBaseTypes(tupleMatch[1]));
259
- return types;
260
- }
261
-
262
- // Handle Record
263
- const recordMatch = typeName.match(/^Record<(.+),\s*(.+)>$/);
264
- if (recordMatch) {
265
- types.push(...this.extractBaseTypes(recordMatch[1]));
266
- types.push(...this.extractBaseTypes(recordMatch[2]));
267
- return types;
268
- }
269
-
270
- // Handle union types
271
- if (typeName.includes(' | ')) {
272
- const parts = typeName.split(' | ');
273
- for (const part of parts) {
274
- types.push(...this.extractBaseTypes(part.trim()));
275
- }
276
- return types;
277
- }
278
-
279
- // Base case - simple type
280
- types.push(typeName);
281
- return types;
282
- }
283
-
284
- private generateTypeInfo(schema: Schema): TypeInfo {
285
- if (Array.isArray(schema)) {
286
- return this.processArraySchema(schema);
287
- } else if (typeof schema === 'string') {
288
- return this.processPrimitiveSchema(schema);
289
- } else if (typeof schema === 'object') {
290
- return this.processObjectSchema(schema);
291
- }
292
- throw new Error(`Unsupported schema type: ${schema}`);
293
- }
294
-
295
- private processArraySchema(schema: any[]): TypeInfo {
296
- const [type, ...args] = schema;
297
-
298
- switch (type) {
299
- case 'array': {
300
- const [subtype, size] = args[0];
301
- // Special case: byte arrays should be Uint8Array
302
- if (subtype === 'unsigned char') {
303
- return { typeName: 'Uint8Array' };
304
- }
305
- // For other types, use T[] - idiomatic TypeScript for fixed-length homogeneous arrays
306
- const subtypeInfo = this.processSchema(subtype);
307
- return {
308
- typeName: `${subtypeInfo.typeName}[]`,
309
- msgpackTypeName: `${subtypeInfo.msgpackTypeName || subtypeInfo.typeName}[]`,
310
- };
311
- }
312
-
313
- case 'variant': {
314
- const variants = args[0] as Schema[];
315
- const variantInfos = variants.map(v => this.processSchema(v));
316
- const typeName = variantInfos.map(v => v.typeName).join(' | ');
317
- const msgpackUnion = variantInfos.map(v => v.msgpackTypeName || v.typeName).join(' | ');
318
- return {
319
- typeName,
320
- msgpackTypeName: `[number, ${msgpackUnion}]`,
321
- };
322
- }
323
-
324
- case 'named_union': {
325
- const namedTypes = args[0] as Array<[string, Schema]>;
326
- const tupleTypes: string[] = [];
327
-
328
- for (const [name, schemaOrName] of namedTypes) {
329
- let typeInfo = this.processSchema(schemaOrName);
330
- // Track usage of the type
331
- this.trackTypeUsage(typeInfo.typeName);
332
- tupleTypes.push(`["${name}", ${typeInfo.typeName}]`);
333
- }
334
-
335
- return {
336
- typeName: tupleTypes.join(' | '),
337
- msgpackTypeName: tupleTypes.join(' | '),
338
- };
339
- }
340
-
341
- case 'vector': {
342
- const [subtype] = args[0];
343
- if (subtype === 'unsigned char') {
344
- return { typeName: 'Uint8Array' };
345
- }
346
- const subtypeInfo = this.processSchema(subtype);
347
- return {
348
- typeName: `${subtypeInfo.typeName}[]`,
349
- msgpackTypeName: `${subtypeInfo.msgpackTypeName || subtypeInfo.typeName}[]`,
350
- };
351
- }
352
-
353
- case 'alias': {
354
- const [rawTypeName, msgpackName] = args[0];
355
- const typeName = pascalCase(rawTypeName);
356
- let targetType: string;
357
-
358
- if (msgpackName.startsWith('bin')) {
359
- targetType = 'Uint8Array';
360
- } else if (['int', 'unsigned int', 'unsigned short'].includes(msgpackName)) {
361
- targetType = 'number';
362
- } else {
363
- throw new Error(`Unsupported alias type: ${msgpackName}`);
364
- }
365
-
366
- // Create a proper type alias declaration
367
- return {
368
- typeName,
369
- msgpackTypeName: targetType,
370
- declaration: `export type ${typeName} = ${targetType};`,
371
- };
372
- }
373
-
374
- case 'shared_ptr': {
375
- const [subtype] = args[0];
376
- return this.processSchema(subtype);
377
- }
378
-
379
- case 'map': {
380
- const [keyType, valueType] = args[0];
381
- const keyInfo = this.processSchema(keyType);
382
- const valueInfo = this.processSchema(valueType);
383
- return {
384
- typeName: `Record<${keyInfo.typeName}, ${valueInfo.typeName}>`,
385
- msgpackTypeName: `Record<${keyInfo.msgpackTypeName || keyInfo.typeName}, ${valueInfo.msgpackTypeName || valueInfo.typeName}>`,
386
- };
387
- }
388
-
389
- default:
390
- throw new Error(`Unsupported array schema type: ${type}`);
391
- }
392
- }
393
-
394
- private processPrimitiveSchema(schema: string): TypeInfo {
395
- switch (schema) {
396
- case 'bool':
397
- return { typeName: 'boolean' };
398
- case 'int':
399
- case 'unsigned int':
400
- case 'unsigned short':
401
- case 'unsigned long':
402
- case 'unsigned char':
403
- case 'double':
404
- return { typeName: 'number' };
405
- case 'string':
406
- return { typeName: 'string' };
407
- case 'bin32':
408
- return { typeName: 'Uint8Array' };
409
- case 'field2':
410
- // field2 is an extension field type (fq2) represented as a tuple of two Uint8Arrays
411
- return {
412
- typeName: 'Field2',
413
- msgpackTypeName: '[Uint8Array, Uint8Array]',
414
- declaration: 'export type Field2 = [Uint8Array, Uint8Array];',
415
- };
416
- default:
417
- return { typeName: pascalCase(schema) };
418
- }
419
- }
420
-
421
- private processObjectSchema(schema: ObjectSchema): TypeInfo {
422
- const typeName = pascalCase(schema.__typename as string);
423
- const msgpackTypeName = 'Msgpack' + typeName;
424
-
425
- const declaration = this.generateInterfaces(typeName, schema);
426
- const toMethod = this.generateToMethod(typeName, schema);
427
- const fromMethod = this.generateFromMethod(typeName, schema);
428
-
429
- return {
430
- typeName,
431
- msgpackTypeName,
432
- declaration,
433
- toMethod,
434
- fromMethod,
435
- };
436
- }
437
-
438
- private getOrCreateEmptyType(typeName: string): TypeInfo {
439
- const key = `empty_${typeName}`;
440
- if (this.typeCache.has(key)) {
441
- return this.typeCache.get(key)!;
442
- }
443
-
444
- const typeInfo: TypeInfo = {
445
- typeName,
446
- msgpackTypeName: 'Msgpack' + typeName,
447
- declaration: `export interface ${typeName} {}\n\ninterface Msgpack${typeName} {}`,
448
- toMethod: `function to${typeName}(o: Msgpack${typeName}): ${typeName} {\n return {};\n}`,
449
- fromMethod: `function from${typeName}(o: ${typeName}): Msgpack${typeName} {\n return {};\n}`,
450
- };
451
-
452
- this.typeCache.set(key, typeInfo);
453
- return typeInfo;
454
- }
455
-
456
- private generateInterfaces(name: string, schema: ObjectSchema): string {
457
- const publicInterface = this.generatePublicInterface(name, schema);
458
- const msgpackInterface = this.generateMsgpackInterface(name, schema);
459
- return publicInterface + '\n\n' + msgpackInterface;
460
- }
461
-
462
- private generatePublicInterface(name: string, schema: ObjectSchema): string {
463
- let result = `export interface ${name} {\n`;
464
- for (const [key, value] of Object.entries(schema)) {
465
- if (key === '__typename') continue;
466
- const typeInfo = this.processSchema(value);
467
-
468
- // Track type usage
469
- this.trackTypeUsage(typeInfo.typeName);
470
-
471
- result += ` ${camelCase(key)}: ${typeInfo.typeName};\n`;
472
- }
473
- result += '}';
474
- return result;
475
- }
476
-
477
- private generateMsgpackInterface(name: string, schema: ObjectSchema): string {
478
- let result = `interface Msgpack${name} {\n`;
479
- for (const [key, value] of Object.entries(schema)) {
480
- if (key === '__typename') continue;
481
- const typeInfo = this.processSchema(value);
482
- result += ` ${key}: ${typeInfo.msgpackTypeName || typeInfo.typeName};\n`;
483
- }
484
- result += '}';
485
- return result;
486
- }
487
-
488
- private generateToMethod(name: string, schema: ObjectSchema): string {
489
- const fields = Object.entries(schema).filter(([key]) => key !== '__typename');
490
-
491
- if (fields.length === 0) {
492
- return `function to${name}(o: Msgpack${name}): ${name} {\n return {};\n}`;
493
- }
494
-
495
- const checks = fields
496
- .map(
497
- ([key]) => ` if (o.${key} === undefined) { throw new Error("Expected ${key} in ${name} deserialization"); }`,
498
- )
499
- .join('\n');
500
-
501
- const conversions = fields
502
- .map(([key, value]) => {
503
- const typeInfo = this.processSchema(value);
504
- const converter = this.generateConverter(typeInfo, `o.${key}`, 'to');
505
- return ` ${camelCase(key)}: ${converter},`;
506
- })
507
- .join('\n');
508
-
509
- return `function to${name}(o: Msgpack${name}): ${name} {
510
- ${checks};
511
- return {
512
- ${conversions}
513
- };
514
- }`;
515
- }
516
-
517
- private generateFromMethod(name: string, schema: ObjectSchema): string {
518
- const fields = Object.entries(schema).filter(([key]) => key !== '__typename');
519
-
520
- if (fields.length === 0) {
521
- return `function from${name}(o: ${name}): Msgpack${name} {\n return {};\n}`;
522
- }
523
-
524
- const checks = fields
525
- .map(
526
- ([key]) =>
527
- ` if (o.${camelCase(key)} === undefined) { throw new Error("Expected ${camelCase(key)} in ${name} serialization"); }`,
528
- )
529
- .join('\n');
530
-
531
- const conversions = fields
532
- .map(([key, value]) => {
533
- const typeInfo = this.processSchema(value);
534
- const converter = this.generateConverter(typeInfo, `o.${camelCase(key)}`, 'from');
535
- return ` ${key}: ${converter},`;
536
- })
537
- .join('\n');
538
-
539
- return `function from${name}(o: ${name}): Msgpack${name} {
540
- ${checks};
541
- return {
542
- ${conversions}
543
- };
544
- }`;
545
- }
546
-
547
- private generateConverter(typeInfo: TypeInfo, value: string, direction: 'to' | 'from'): string {
548
- // Handle arrays/tuples
549
- if (typeInfo.typeName.includes('[]') || typeInfo.typeName.includes('Tuple<')) {
550
- const elementType = typeInfo.typeName.match(/^(.+)\[\]$/) || typeInfo.typeName.match(/^Tuple<(.+),/);
551
- if (elementType) {
552
- const isTuple = typeInfo.typeName.includes('Tuple<');
553
- const mapFn = isTuple ? 'mapTuple' : 'map';
554
- return `${value}.${mapFn}((v: any) => v)`; // Simplified for now
555
- }
556
- }
557
-
558
- // Handle custom types that have conversion methods (not just type aliases)
559
- if (typeInfo.toMethod || typeInfo.fromMethod) {
560
- return `${direction}${typeInfo.typeName}(${value})`;
561
- }
562
-
563
- return value;
564
- }
565
-
566
- private generateImports(): string[] {
567
- const imports: string[] = [];
568
-
569
- // Base imports
570
- if (this.config.imports) {
571
- imports.push(...this.config.imports);
572
- }
573
-
574
- // For API modes, import from api_types
575
- if (this.config.mode !== 'types') {
576
- const neededImports = new Set<string>();
577
-
578
- // Add types and conversion functions from function metadata
579
- for (const metadata of this.functionMetadata) {
580
- neededImports.add(metadata.commandType);
581
- neededImports.add(metadata.responseType);
582
- neededImports.add(`from${metadata.commandType}`);
583
- neededImports.add(`to${metadata.responseType}`);
584
- }
585
-
586
- // Add referenced types
587
- for (const type of this.referencedTypes) {
588
- neededImports.add(type);
589
- }
590
-
591
- // Add BbApiBase interface
592
- neededImports.add('BbApiBase');
593
-
594
- if (neededImports.size > 0) {
595
- const sortedImports = Array.from(neededImports).sort();
596
- // Remove duplicates
597
- const uniqueImports = sortedImports.filter((item, index) => sortedImports.indexOf(item) === index);
598
- imports.push(`import { ${uniqueImports.join(', ')} } from './api_types.js';`);
599
- }
600
- }
601
-
602
- return imports;
603
- }
604
-
605
- private generateBbApiBaseInterface(): string {
606
- const methods = this.functionMetadata
607
- .map(m => ` ${m.name}(command: ${m.commandType}): Promise<${m.responseType}>;`)
608
- .join('\n');
609
-
610
- return `export interface BbApiBase {
611
- ${methods}
612
- destroy(): Promise<void>;
613
- }`;
614
- }
615
-
616
- private generateApiClass(): string {
617
- const className = this.getApiClassName();
618
- const methods = this.functionMetadata.map(m => this.generateApiMethod(m)).join('\n\n');
619
-
620
- // For sync API, don't implement BbApiBase since methods are synchronous
621
- const implementsClause = this.config.mode === 'sync' ? '' : ' implements BbApiBase';
622
-
623
- // For tracing all calls to bb.
624
- // const msgpackCallHelper =
625
- // `${this.config.mode === 'async' ? 'async ' : ''}function msgpackCall(backend: ${this.getBackendType()}, input: any[]) {\n` +
626
- // ` const commandName = input[0]?.[0] || 'unknown';\n` +
627
- // ` process.stderr.write(\`[BB MSGPACK ${this.config.mode === 'async' ? 'ASYNC' : 'SYNC'}] \${commandName}\\n\`);\n` +
628
- // ` const inputBuffer = new Encoder({ useRecords: false }).pack(input);\n` +
629
- // ` const encodedResult = ${this.config.mode === 'async' ? 'await ' : ''}backend.call(inputBuffer);\n` +
630
- // ` const result = new Decoder({ useRecords: false }).unpack(encodedResult);\n` +
631
- // ` process.stderr.write(\`[BB MSGPACK ${this.config.mode === 'async' ? 'ASYNC' : 'SYNC'}] \${commandName} => completed\\n\`);\n` +
632
- // ` return result;\n` +
633
- // `}\n`;
634
- const msgpackCallHelper =
635
- `${this.config.mode === 'async' ? 'async ' : ''}function msgpackCall(backend: ${this.getBackendType()}, input: any[]) {` +
636
- ` const inputBuffer = new Encoder({ useRecords: false }).pack(input);` +
637
- ` const encodedResult = ${this.config.mode === 'async' ? 'await ' : ''}backend.call(inputBuffer);` +
638
- ` return new Decoder({ useRecords: false }).unpack(encodedResult);` +
639
- `}\n`;
640
- const destroyMethod =
641
- this.config.mode === 'sync'
642
- ? ` destroy(): void {
643
- if (this.backend.destroy) this.backend.destroy();
644
- }`
645
- : ` destroy(): Promise<void> {
646
- return this.backend.destroy ? this.backend.destroy() : Promise.resolve();
647
- }`;
648
-
649
- return (
650
- msgpackCallHelper +
651
- `export class ${className}${implementsClause} {
652
- constructor(protected backend: ${this.getBackendType()}) {}
653
-
654
- ${methods}
655
-
656
- ${destroyMethod}
657
- }`
658
- );
659
- }
660
-
661
- private getApiClassName(): string {
662
- switch (this.config.mode) {
663
- case 'sync':
664
- return 'SyncApi';
665
- case 'async':
666
- return 'AsyncApi';
667
- default:
668
- throw new Error(`Invalid mode: ${this.config.mode}`);
669
- }
670
- }
671
-
672
- private getBackendType(): string {
673
- switch (this.config.mode) {
674
- case 'sync':
675
- return 'IMsgpackBackendSync';
676
- case 'async':
677
- return 'IMsgpackBackendAsync';
678
- default:
679
- return '';
680
- }
681
- }
682
-
683
- private generateApiMethod(metadata: FunctionMetadata): string {
684
- const { name, commandType, responseType } = metadata;
685
-
686
- // For async mode, queue immediately and return promise
687
- if (this.config.mode === 'async') {
688
- return ` ${name}(command: ${commandType}): Promise<${responseType}> {
689
- const msgpackCommand = from${commandType}(command);
690
- return msgpackCall(this.backend, [["${capitalize(name)}", msgpackCommand]]).then(([variantName, result]: [string, any]) => {
691
- if (variantName === 'ErrorResponse') {
692
- throw new BBApiException(result.message || 'Unknown error from barretenberg');
693
- }
694
- if (variantName !== '${responseType}') {
695
- throw new BBApiException(\`Expected variant name '${responseType}' but got '\${variantName}'\`);
696
- }
697
- return to${responseType}(result);
698
- });
699
- }`;
700
- }
701
-
702
- // For sync mode, keep the synchronous behavior
703
- return ` ${name}(command: ${commandType}): ${responseType} {
704
- const msgpackCommand = from${commandType}(command);
705
- const [variantName, result] = msgpackCall(this.backend, [["${capitalize(name)}", msgpackCommand]]);
706
- if (variantName === 'ErrorResponse') {
707
- throw new BBApiException(result.message || 'Unknown error from barretenberg');
708
- }
709
- if (variantName !== '${responseType}') {
710
- throw new BBApiException(\`Expected variant name '${responseType}' but got '\${variantName}'\`);
711
- }
712
- return to${responseType}(result);
713
- }`;
714
- }
715
- }
716
-
717
- // Factory methods for creating configured compilers
718
- export function createSharedTypesCompiler(): SchemaCompiler {
719
- return new SchemaCompiler({
720
- mode: 'types',
721
- imports: [],
722
- });
723
- }
724
-
725
- export function createSyncApiCompiler(): SchemaCompiler {
726
- return new SchemaCompiler({
727
- mode: 'sync',
728
- imports: [
729
- `import { IMsgpackBackendSync } from '../../bb_backends/interface.js';`,
730
- `import { Decoder, Encoder } from 'msgpackr';`,
731
- `import { BBApiException } from '../../bbapi_exception.js';`,
732
- ],
733
- });
734
- }
735
-
736
- export function createAsyncApiCompiler(): SchemaCompiler {
737
- return new SchemaCompiler({
738
- mode: 'async',
739
- imports: [
740
- `import { IMsgpackBackendAsync } from '../../bb_backends/interface.js';`,
741
- `import { Decoder, Encoder } from 'msgpackr';`,
742
- `import { BBApiException } from '../../bbapi_exception.js';`,
743
- ],
744
- });
745
- }