@ic-reactor/codegen 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,16 +54,17 @@ need to skip `index.generated.ts` and `index.ts`.
54
54
 
55
55
  You can also use individual generators if you need more granular control:
56
56
 
57
- - **`generateDeclarations`**: Generates `.js` (factory), `.d.ts` (types), and `.did` copy.
58
- - **`generateReactorFile`**: Generates the managed `index.generated.ts` implementation using either `DisplayReactor` or `Reactor`.
57
+ - **`generateDeclarations`**: Writes `declarations/<did-basename>.js` (factory), `.d.ts` (types), and a `.did` copy. The `declarations/` directory is wiped and recreated on every run.
58
+ - **`generateReactorFile`**: Generates the managed `index.generated.ts` implementation using any `ReactorClassName` — `Reactor`, `DisplayReactor` (default), `CandidReactor`, `CandidDisplayReactor`, or `MetadataDisplayReactor`. With `target: "react"` it also emits the six `createActorHooks` exports (`use<Canister>Query`, `use<Canister>SuspenseQuery`, `use<Canister>InfiniteQuery`, `use<Canister>SuspenseInfiniteQuery`, `use<Canister>Mutation`, `use<Canister>Method`). No `createQuery` / `createMutation` objects are generated.
59
59
  - **`generateReactorEntryFile`**: Generates the stable `index.ts` wrapper that re-exports from `index.generated.ts`.
60
60
  - **`generateClientFile`**: Generates a `ClientManager` boilerplate file that
61
61
  imports `ClientManager` from `@ic-reactor/react`.
62
62
 
63
63
  ## Utilities
64
64
 
65
- - **`parseDIDFile`**: Parses a `.did` file and extracts method signatures.
66
- - **`toPascalCase` / `toCamelCase`**: Naming helpers.
65
+ - **`parseDIDFile` / `extractMethods`**: Parse a `.did` file and extract method signatures.
66
+ - **`toPascalCase` / `getReactorName` / `getServiceTypeName`**: Naming helpers.
67
+ - **`generateCodecDeclarations`**: Renders a `@ic-reactor/cod` codec module from Candid (also available on the `./renderer` subpath).
67
68
 
68
69
  ## License
69
70
 
@@ -0,0 +1,609 @@
1
+ // src/metadata-rules.json
2
+ var metadata_rules_default = {
3
+ defaultValidationMessages: {
4
+ minimum: {
5
+ template: "Must be at least {value}"
6
+ },
7
+ maximum: {
8
+ template: "Must be at most {value}"
9
+ },
10
+ minLength: {
11
+ template: "Must be at least {value} character{plural}"
12
+ },
13
+ maxLength: {
14
+ template: "Must be at most {value} character{plural}"
15
+ }
16
+ },
17
+ email: {
18
+ helper: "email",
19
+ regex: "^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$",
20
+ jsonSchemaFormat: "email",
21
+ errorMessage: "Must be a valid email address"
22
+ },
23
+ "date-time": {
24
+ helper: "dateTime",
25
+ regex: "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d))$",
26
+ jsonSchemaFormat: "date-time",
27
+ errorMessage: "Must be a valid ISO datetime"
28
+ },
29
+ datetime: {
30
+ helper: "datetime",
31
+ regex: "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|[+-](?:[01]\\d|2[0-3]):[0-5]\\d))$",
32
+ jsonSchemaFormat: "date-time",
33
+ errorMessage: "Must be a valid ISO datetime"
34
+ },
35
+ date: {
36
+ helper: "date",
37
+ regex: "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$",
38
+ jsonSchemaFormat: "date",
39
+ errorMessage: "Must be a valid ISO date"
40
+ },
41
+ time: {
42
+ helper: "time",
43
+ regex: "^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?$",
44
+ errorMessage: "Must be a valid ISO time"
45
+ },
46
+ duration: {
47
+ helper: "duration",
48
+ regex: "^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$",
49
+ jsonSchemaFormat: "duration",
50
+ errorMessage: "Must be a valid ISO duration"
51
+ },
52
+ url: {
53
+ helper: "url",
54
+ regex: "^[a-zA-Z][a-zA-Z\\d+.-]*:.+",
55
+ jsonSchemaFormat: "uri",
56
+ errorMessage: "Must be a valid URL"
57
+ },
58
+ uri: {
59
+ helper: "uri",
60
+ regex: "^[a-zA-Z][a-zA-Z\\d+.-]*:.+",
61
+ jsonSchemaFormat: "uri",
62
+ errorMessage: "Must be a valid URI"
63
+ },
64
+ httpsUrl: {
65
+ helper: "httpsUrl",
66
+ regex: "^https://.+",
67
+ jsonSchemaFormat: "uri",
68
+ errorMessage: "Must be a valid HTTPS URL"
69
+ },
70
+ ipv4: {
71
+ helper: "ipv4",
72
+ regex: "^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.|$)){4}$",
73
+ jsonSchemaFormat: "ipv4",
74
+ errorMessage: "Must be a valid IPv4 address"
75
+ },
76
+ ipv6: {
77
+ helper: "ipv6",
78
+ regex: "^((?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|::1|::|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,5}(?::[0-9A-Fa-f]{1,4}){1,2}|(?:[0-9A-Fa-f]{1,4}:){1,4}(?::[0-9A-Fa-f]{1,4}){1,3}|(?:[0-9A-Fa-f]{1,4}:){1,3}(?::[0-9A-Fa-f]{1,4}){1,4}|(?:[0-9A-Fa-f]{1,4}:){1,2}(?::[0-9A-Fa-f]{1,4}){1,5}|[0-9A-Fa-f]{1,4}:(?:(?::[0-9A-Fa-f]{1,4}){1,6}))$",
79
+ jsonSchemaFormat: "ipv6",
80
+ errorMessage: "Must be a valid IPv6 address"
81
+ },
82
+ uuid: {
83
+ helper: "uuid",
84
+ regex: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
85
+ jsonSchemaFormat: "uuid",
86
+ errorMessage: "Must be a valid UUID"
87
+ },
88
+ guid: {
89
+ helper: "guid",
90
+ regex: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",
91
+ jsonSchemaFormat: "uuid",
92
+ errorMessage: "Must be a valid GUID"
93
+ },
94
+ base64: {
95
+ helper: "base64",
96
+ regex: "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$",
97
+ contentEncoding: "base64",
98
+ errorMessage: "Must be valid base64"
99
+ },
100
+ base64url: {
101
+ helper: "base64url",
102
+ regex: "^[A-Za-z0-9_-]+$",
103
+ errorMessage: "Must be valid base64url"
104
+ },
105
+ cuid: {
106
+ helper: "cuid",
107
+ regex: "^c[a-z0-9]{24}$",
108
+ errorMessage: "Must be a valid CUID"
109
+ },
110
+ cuid2: {
111
+ helper: "cuid2",
112
+ regex: "^[a-z][a-z0-9]*$",
113
+ errorMessage: "Must be a valid CUID2"
114
+ },
115
+ ulid: {
116
+ helper: "ulid",
117
+ regex: "^[0-9A-HJKMNP-TV-Z]{26}$",
118
+ errorMessage: "Must be a valid ULID"
119
+ },
120
+ nanoid: {
121
+ helper: "nanoid",
122
+ regex: "^[A-Za-z0-9_-]{21}$",
123
+ errorMessage: "Must be a valid nanoid"
124
+ },
125
+ emoji: {
126
+ helper: "emoji",
127
+ regex: "^\\p{Extended_Pictographic}+$",
128
+ errorMessage: "Must contain only emoji characters"
129
+ },
130
+ cidrv4: {
131
+ helper: "cidrv4",
132
+ regex: "^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)/(?:3[0-2]|[12]?\\d)$",
133
+ errorMessage: "Must be a valid IPv4 CIDR range"
134
+ },
135
+ cidrv6: {
136
+ helper: "cidrv6",
137
+ regex: "^[0-9A-Fa-f:]+/(?:12[0-8]|1[01]\\d|\\d?\\d)$",
138
+ errorMessage: "Must be a valid IPv6 CIDR range"
139
+ },
140
+ mac: {
141
+ helper: "mac",
142
+ regex: "^(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$",
143
+ errorMessage: "Must be a valid MAC address"
144
+ }
145
+ };
146
+
147
+ // src/metadata.ts
148
+ var metadataRulesFile = metadata_rules_default;
149
+ var defaultValidationMessages = metadataRulesFile.defaultValidationMessages ?? {};
150
+ var rawRuleEntries = Object.entries(metadata_rules_default).filter(
151
+ ([type]) => type !== "defaultValidationMessages"
152
+ );
153
+ var BUILT_IN_JSDOC_FORMAT_TYPES = Object.fromEntries(
154
+ rawRuleEntries.map(([type, rule]) => [
155
+ type,
156
+ {
157
+ regex: rule.regex,
158
+ jsonSchemaFormat: rule.jsonSchemaFormat,
159
+ contentEncoding: rule.contentEncoding,
160
+ errorMessage: rule.errorMessage
161
+ }
162
+ ])
163
+ );
164
+ var BUILT_IN_FORMAT_HELPERS = Object.fromEntries(
165
+ rawRuleEntries.filter(([, rule]) => rule.helper).map(([type, rule]) => [type, rule.helper])
166
+ );
167
+ function normalizeFormatDefinition(definition) {
168
+ if (!definition) return void 0;
169
+ return typeof definition === "string" ? { regex: definition } : definition;
170
+ }
171
+ function formatDefinitionFor(type, options) {
172
+ const builtIn = BUILT_IN_JSDOC_FORMAT_TYPES[type];
173
+ const custom = normalizeFormatDefinition(
174
+ options.customJSDocFormatTypes?.[type]
175
+ );
176
+ if (!custom) return builtIn;
177
+ return {
178
+ ...builtIn,
179
+ ...custom,
180
+ errorMessage: custom.errorMessage ?? builtIn?.errorMessage
181
+ };
182
+ }
183
+ function stripUndefined(value) {
184
+ return Object.fromEntries(
185
+ Object.entries(value).filter(([, entry]) => entry !== void 0)
186
+ );
187
+ }
188
+ function defaultBoundMessage(kind, value) {
189
+ const template = defaultValidationMessages[kind]?.template ?? (kind === "minimum" ? "Must be at least {value}" : kind === "maximum" ? "Must be at most {value}" : kind === "minLength" ? "Must be at least {value} character{plural}" : "Must be at most {value} character{plural}");
190
+ return template.replace("{value}", value).replace("{plural}", value === "1" ? "" : "s");
191
+ }
192
+ function withDefaultBoundMessage(bound, kind) {
193
+ if (!bound || bound.message !== void 0) return bound;
194
+ return {
195
+ ...bound,
196
+ message: defaultBoundMessage(kind, bound.value)
197
+ };
198
+ }
199
+ function normalizeValidationMetadata(validation, options) {
200
+ const normalized = {
201
+ ...validation,
202
+ minimum: withDefaultBoundMessage(validation.minimum, "minimum"),
203
+ maximum: withDefaultBoundMessage(validation.maximum, "maximum"),
204
+ minLength: withDefaultBoundMessage(validation.minLength, "minLength"),
205
+ maxLength: withDefaultBoundMessage(validation.maxLength, "maxLength")
206
+ };
207
+ const format = validation.format;
208
+ const formatDefinition = format ? formatDefinitionFor(format.type, options) : void 0;
209
+ if (format && formatDefinition) {
210
+ normalized.format = stripUndefined({
211
+ ...format,
212
+ regex: formatDefinition.regex,
213
+ jsonSchemaFormat: formatDefinition.jsonSchemaFormat,
214
+ contentEncoding: formatDefinition.contentEncoding,
215
+ errorMessage: format.message ?? formatDefinition.errorMessage
216
+ });
217
+ } else if (format) {
218
+ normalized.format = format;
219
+ }
220
+ return normalized;
221
+ }
222
+
223
+ // src/renderer.ts
224
+ var reservedWords = /* @__PURE__ */ new Set([
225
+ "break",
226
+ "case",
227
+ "catch",
228
+ "class",
229
+ "const",
230
+ "continue",
231
+ "debugger",
232
+ "default",
233
+ "delete",
234
+ "do",
235
+ "else",
236
+ "export",
237
+ "extends",
238
+ "false",
239
+ "finally",
240
+ "for",
241
+ "function",
242
+ "if",
243
+ "import",
244
+ "in",
245
+ "instanceof",
246
+ "new",
247
+ "null",
248
+ "return",
249
+ "super",
250
+ "switch",
251
+ "this",
252
+ "throw",
253
+ "true",
254
+ "try",
255
+ "typeof",
256
+ "var",
257
+ "void",
258
+ "while",
259
+ "with",
260
+ "yield",
261
+ "let",
262
+ "package",
263
+ "private",
264
+ "protected",
265
+ "public",
266
+ "static"
267
+ ]);
268
+ function isValidIdentifier(name) {
269
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) && !reservedWords.has(name);
270
+ }
271
+ function assertIdentifier(name, label) {
272
+ if (!isValidIdentifier(name)) {
273
+ throw new Error(`${label} must be a valid TypeScript identifier: ${name}`);
274
+ }
275
+ }
276
+ function propertyName(name) {
277
+ return isValidIdentifier(name) ? name : JSON.stringify(name);
278
+ }
279
+ function normalizeOptions(options = {}) {
280
+ return typeof options === "string" ? { serviceExportName: options } : options;
281
+ }
282
+ function toServiceExportName(canisterName) {
283
+ return canisterName.replace(/[-\s]+/g, "_").toUpperCase();
284
+ }
285
+ function resolveServiceExportName(options, declaredTypeNames) {
286
+ if (options.serviceExportName) return options.serviceExportName;
287
+ if (options.canisterName) {
288
+ let name = toServiceExportName(options.canisterName);
289
+ if (declaredTypeNames.has(name)) {
290
+ name = `${name}_SERVICE`;
291
+ }
292
+ return name;
293
+ }
294
+ return "_SERVICE";
295
+ }
296
+ function hasMetadata(metadata) {
297
+ return metadata != null && Object.keys(metadata).length > 0;
298
+ }
299
+ function stripUndefined2(value) {
300
+ return Object.fromEntries(
301
+ Object.entries(value).filter(([, entry]) => entry !== void 0)
302
+ );
303
+ }
304
+ function isEmptyObject(value) {
305
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
306
+ }
307
+ function textFormatHelperFor(expression, metadata, options) {
308
+ const format = metadata.validation?.format;
309
+ if (!format || expression !== "c.text()") return void 0;
310
+ if (options.customJSDocFormatTypes?.[format.type]) {
311
+ return void 0;
312
+ }
313
+ return BUILT_IN_FORMAT_HELPERS[format.type];
314
+ }
315
+ function hasOnlyDescriptionDocs(docs, description) {
316
+ return docs != null && description != null && docs.length === 1 && docs[0] === description;
317
+ }
318
+ function metadataForRender(metadata, options) {
319
+ if (!metadata.validation) {
320
+ return metadata;
321
+ }
322
+ return {
323
+ ...metadata,
324
+ validation: normalizeValidationMetadata(metadata.validation, {
325
+ customJSDocFormatTypes: options.customJSDocFormatTypes
326
+ })
327
+ };
328
+ }
329
+ function applyMetadata(expression, metadata, options) {
330
+ if (!hasMetadata(metadata)) return expression;
331
+ const textFormatHelper = textFormatHelperFor(expression, metadata, options);
332
+ const textFormatMessage = metadata.validation?.format?.message;
333
+ const renderedMetadata = metadataForRender(metadata, options);
334
+ const { description, ...metadataRest } = renderedMetadata;
335
+ const rest = { ...metadataRest };
336
+ let result = textFormatHelper ? `c.${textFormatHelper}(${textFormatMessage ? JSON.stringify(textFormatMessage) : ""})` : expression;
337
+ if (textFormatHelper) {
338
+ delete rest.docs;
339
+ if (rest.validation) {
340
+ const { format: _format, ...validationRest } = rest.validation;
341
+ rest.validation = stripUndefined2(validationRest);
342
+ if (isEmptyObject(rest.validation)) {
343
+ delete rest.validation;
344
+ }
345
+ }
346
+ } else if (hasOnlyDescriptionDocs(rest.docs, description)) {
347
+ delete rest.docs;
348
+ }
349
+ if (description) {
350
+ result += `.describe(${JSON.stringify(description)})`;
351
+ }
352
+ if (Object.keys(rest).length > 0) {
353
+ result += `.meta(${JSON.stringify(rest)})`;
354
+ }
355
+ return result;
356
+ }
357
+ function getReferencedNames(type) {
358
+ const refs = [];
359
+ function visit(node) {
360
+ switch (node.kind) {
361
+ case "reference":
362
+ refs.push(node.name);
363
+ break;
364
+ case "opt":
365
+ case "vec":
366
+ visit(node.type);
367
+ break;
368
+ case "record":
369
+ case "variant":
370
+ for (const field of node.fields) {
371
+ visit(field.type);
372
+ }
373
+ break;
374
+ case "tuple":
375
+ for (const item of node.types) {
376
+ visit(item);
377
+ }
378
+ break;
379
+ }
380
+ }
381
+ visit(type);
382
+ return refs;
383
+ }
384
+ function sortDeclarations(declarations) {
385
+ const sorted = [];
386
+ const visited = /* @__PURE__ */ new Set();
387
+ const visiting = [];
388
+ const declarationByName = new Map(
389
+ declarations.map((decl) => [decl.name, decl])
390
+ );
391
+ function visit(name) {
392
+ if (visited.has(name)) return;
393
+ const cycleStart = visiting.indexOf(name);
394
+ if (cycleStart !== -1) {
395
+ const cycle = [...visiting.slice(cycleStart), name].join(" -> ");
396
+ throw new Error(`Recursive Candid types are not supported yet: ${cycle}`);
397
+ }
398
+ const declaration = declarationByName.get(name);
399
+ if (!declaration) return;
400
+ visiting.push(name);
401
+ for (const dependency of getReferencedNames(declaration.type)) {
402
+ visit(dependency);
403
+ }
404
+ visiting.pop();
405
+ visited.add(name);
406
+ sorted.push(declaration);
407
+ }
408
+ for (const declaration of declarations) {
409
+ visit(declaration.name);
410
+ }
411
+ return sorted;
412
+ }
413
+ function renderType(type, indent = "", options = {}) {
414
+ const nextIndent = `${indent} `;
415
+ let expression;
416
+ switch (type.kind) {
417
+ case "null":
418
+ expression = "c.null()";
419
+ break;
420
+ case "bool":
421
+ expression = "c.bool()";
422
+ break;
423
+ case "nat":
424
+ expression = "c.nat()";
425
+ break;
426
+ case "int":
427
+ expression = "c.int()";
428
+ break;
429
+ case "nat8":
430
+ expression = "c.nat8()";
431
+ break;
432
+ case "nat16":
433
+ expression = "c.nat16()";
434
+ break;
435
+ case "nat32":
436
+ expression = "c.nat32()";
437
+ break;
438
+ case "nat64":
439
+ expression = "c.nat64()";
440
+ break;
441
+ case "int8":
442
+ expression = "c.int8()";
443
+ break;
444
+ case "int16":
445
+ expression = "c.int16()";
446
+ break;
447
+ case "int32":
448
+ expression = "c.int32()";
449
+ break;
450
+ case "int64":
451
+ expression = "c.int64()";
452
+ break;
453
+ case "float32":
454
+ expression = "c.float32()";
455
+ break;
456
+ case "float64":
457
+ expression = "c.float64()";
458
+ break;
459
+ case "text":
460
+ expression = "c.text()";
461
+ break;
462
+ case "reserved":
463
+ expression = "c.reserved()";
464
+ break;
465
+ case "empty":
466
+ expression = "c.empty()";
467
+ break;
468
+ case "principal":
469
+ expression = "c.principal()";
470
+ break;
471
+ case "blob":
472
+ expression = "c.blob()";
473
+ break;
474
+ case "reference":
475
+ assertIdentifier(type.name, "Type reference");
476
+ expression = type.name;
477
+ break;
478
+ case "opt":
479
+ expression = `c.opt(${renderType(type.type, indent, options)})`;
480
+ break;
481
+ case "vec":
482
+ expression = `c.vec(${renderType(type.type, indent, options)})`;
483
+ break;
484
+ case "record": {
485
+ if (type.fields.length === 0) {
486
+ expression = "c.record({})";
487
+ } else {
488
+ const fields = type.fields.map((field) => {
489
+ const fieldExpression = applyMetadata(
490
+ renderType(field.type, nextIndent, options),
491
+ field.metadata,
492
+ options
493
+ );
494
+ return `${nextIndent}${propertyName(field.name)}: ${fieldExpression},`;
495
+ }).join("\n");
496
+ expression = `c.record({
497
+ ${fields}
498
+ ${indent}})`;
499
+ }
500
+ break;
501
+ }
502
+ case "variant": {
503
+ if (type.fields.length === 0) {
504
+ expression = "c.variant({})";
505
+ } else {
506
+ const fields = type.fields.map((field) => {
507
+ const fieldExpression = applyMetadata(
508
+ renderType(field.type, nextIndent, options),
509
+ field.metadata,
510
+ options
511
+ );
512
+ return `${nextIndent}${propertyName(field.name)}: ${fieldExpression},`;
513
+ }).join("\n");
514
+ expression = `c.variant({
515
+ ${fields}
516
+ ${indent}})`;
517
+ }
518
+ break;
519
+ }
520
+ case "tuple":
521
+ expression = `c.tuple([${type.types.map((item) => renderType(item, indent, options)).join(", ")}])`;
522
+ break;
523
+ case "func":
524
+ case "service":
525
+ case "class":
526
+ case "unknown":
527
+ case "knot":
528
+ case "future":
529
+ expression = `/* c.${type.kind} is not supported */ c.reserved()`;
530
+ break;
531
+ }
532
+ return applyMetadata(expression, type.metadata, options);
533
+ }
534
+ function renderMethodReturn(method, options) {
535
+ if (method.mode === "oneway") return "";
536
+ if (method.returns.length === 0) return "";
537
+ if (method.returns.length === 1) {
538
+ return `, ${renderType(method.returns[0], " ", options)}`;
539
+ }
540
+ return `, [${method.returns.map((returnType) => renderType(returnType, " ", options)).join(", ")}]`;
541
+ }
542
+ function generateCodecDeclarations(schema, optionsOrServiceExportName = {}) {
543
+ const options = normalizeOptions(optionsOrServiceExportName);
544
+ const lines = ['import { c } from "@ic-reactor/cod"', ""];
545
+ for (const declaration of sortDeclarations(schema.types)) {
546
+ assertIdentifier(declaration.name, "Type declaration name");
547
+ lines.push(
548
+ `export const ${declaration.name} = ${applyMetadata(
549
+ renderType(declaration.type, "", options),
550
+ declaration.metadata,
551
+ options
552
+ )}`
553
+ );
554
+ lines.push(
555
+ `export type ${declaration.name} = c.infer<typeof ${declaration.name}>`
556
+ );
557
+ lines.push("");
558
+ }
559
+ if (schema.service) {
560
+ const includeCompatibilityExports = options.includeCompatibilityExports ?? false;
561
+ const declaredTypeNames = new Set(schema.types.map((t) => t.name));
562
+ const serviceExportName = resolveServiceExportName(
563
+ options,
564
+ declaredTypeNames
565
+ );
566
+ assertIdentifier(serviceExportName, "Service export name");
567
+ const methods = schema.service.methods.map((method) => {
568
+ const args = method.args.map((arg) => renderType(arg, " ", options)).join(", ");
569
+ const methodExpression = `c.${method.mode}([${args}]${renderMethodReturn(
570
+ method,
571
+ options
572
+ )})`;
573
+ return ` ${propertyName(method.name)}: ${applyMetadata(
574
+ methodExpression,
575
+ method.metadata,
576
+ options
577
+ )},`;
578
+ }).join("\n");
579
+ const serviceExpression = methods.length > 0 ? `c.service({
580
+ ${methods}
581
+ })` : "c.service({})";
582
+ lines.push(
583
+ `export const ${serviceExportName} = ${applyMetadata(
584
+ serviceExpression,
585
+ schema.service.metadata,
586
+ options
587
+ )}`
588
+ );
589
+ lines.push("");
590
+ if (includeCompatibilityExports) {
591
+ lines.push(`export const idlFactory = ${serviceExportName}.idlFactory`);
592
+ lines.push(
593
+ `export type _SERVICE = c.ServiceOf<typeof ${serviceExportName}>`
594
+ );
595
+ lines.push("");
596
+ lines.push(`export const manifest = ${serviceExportName}.manifest()`);
597
+ }
598
+ }
599
+ return `${lines.join("\n").trimEnd()}
600
+ `;
601
+ }
602
+
603
+ export {
604
+ BUILT_IN_JSDOC_FORMAT_TYPES,
605
+ BUILT_IN_FORMAT_HELPERS,
606
+ sortDeclarations,
607
+ renderType,
608
+ generateCodecDeclarations
609
+ };