@ic-reactor/candid 3.0.7-beta.1 → 3.0.8-beta.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.
Files changed (59) hide show
  1. package/README.md +5 -1
  2. package/dist/display-reactor.d.ts +3 -2
  3. package/dist/display-reactor.d.ts.map +1 -1
  4. package/dist/display-reactor.js +6 -0
  5. package/dist/display-reactor.js.map +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/metadata-display-reactor.d.ts +73 -0
  11. package/dist/metadata-display-reactor.d.ts.map +1 -0
  12. package/dist/metadata-display-reactor.js +128 -0
  13. package/dist/metadata-display-reactor.js.map +1 -0
  14. package/dist/visitor/arguments/index.d.ts +69 -0
  15. package/dist/visitor/arguments/index.d.ts.map +1 -0
  16. package/dist/visitor/arguments/index.js +277 -0
  17. package/dist/visitor/arguments/index.js.map +1 -0
  18. package/dist/visitor/arguments/types.d.ts +92 -0
  19. package/dist/visitor/arguments/types.d.ts.map +1 -0
  20. package/dist/visitor/arguments/types.js +2 -0
  21. package/dist/visitor/arguments/types.js.map +1 -0
  22. package/dist/visitor/constants.d.ts +4 -0
  23. package/dist/visitor/constants.d.ts.map +1 -0
  24. package/dist/visitor/constants.js +61 -0
  25. package/dist/visitor/constants.js.map +1 -0
  26. package/dist/visitor/helpers.d.ts +30 -0
  27. package/dist/visitor/helpers.d.ts.map +1 -0
  28. package/dist/visitor/helpers.js +200 -0
  29. package/dist/visitor/helpers.js.map +1 -0
  30. package/dist/visitor/returns/index.d.ts +76 -0
  31. package/dist/visitor/returns/index.d.ts.map +1 -0
  32. package/dist/visitor/returns/index.js +425 -0
  33. package/dist/visitor/returns/index.js.map +1 -0
  34. package/dist/visitor/returns/types.d.ts +142 -0
  35. package/dist/visitor/returns/types.d.ts.map +1 -0
  36. package/dist/visitor/returns/types.js +2 -0
  37. package/dist/visitor/returns/types.js.map +1 -0
  38. package/dist/visitor/types.d.ts +6 -0
  39. package/dist/visitor/types.d.ts.map +1 -0
  40. package/dist/visitor/types.js +3 -0
  41. package/dist/visitor/types.js.map +1 -0
  42. package/package.json +4 -2
  43. package/src/adapter.ts +446 -0
  44. package/src/constants.ts +11 -0
  45. package/src/display-reactor.ts +332 -0
  46. package/src/index.ts +7 -0
  47. package/src/metadata-display-reactor.ts +184 -0
  48. package/src/reactor.ts +199 -0
  49. package/src/types.ts +107 -0
  50. package/src/utils.ts +28 -0
  51. package/src/visitor/arguments/index.test.ts +882 -0
  52. package/src/visitor/arguments/index.ts +405 -0
  53. package/src/visitor/arguments/types.ts +168 -0
  54. package/src/visitor/constants.ts +62 -0
  55. package/src/visitor/helpers.ts +221 -0
  56. package/src/visitor/returns/index.test.ts +2027 -0
  57. package/src/visitor/returns/index.ts +545 -0
  58. package/src/visitor/returns/types.ts +271 -0
  59. package/src/visitor/types.ts +29 -0
package/src/adapter.ts ADDED
@@ -0,0 +1,446 @@
1
+ import type { HttpAgent } from "@icp-sdk/core/agent"
2
+ import type { Principal } from "@icp-sdk/core/principal"
3
+ import type {
4
+ CandidAdapterParameters,
5
+ CandidDefinition,
6
+ CandidClientManager,
7
+ ReactorParser,
8
+ } from "./types"
9
+
10
+ import { CanisterStatus } from "@icp-sdk/core/agent"
11
+ import { IDL } from "@icp-sdk/core/candid"
12
+ import { DEFAULT_IC_DIDJS_ID, DEFAULT_LOCAL_DIDJS_ID } from "./constants"
13
+ import { importCandidDefinition } from "./utils"
14
+ import { CanisterId } from "@ic-reactor/core"
15
+
16
+ /**
17
+ * CandidAdapter provides functionality to fetch and parse Candid definitions
18
+ * from Internet Computer canisters.
19
+ *
20
+ * It supports multiple methods for retrieving Candid definitions:
21
+ * 1. From canister metadata (preferred)
22
+ * 2. From the `__get_candid_interface_tmp_hack` method (fallback)
23
+ *
24
+ * It also supports parsing Candid to JavaScript using:
25
+ * 1. Local WASM parser (@ic-reactor/parser) - faster, no network request
26
+ * 2. Remote didjs canister - always available fallback
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { CandidAdapter } from "@ic-reactor/candid"
31
+ * import { ClientManager } from "@ic-reactor/core"
32
+ * import { QueryClient } from "@tanstack/query-core"
33
+ *
34
+ * const queryClient = new QueryClient()
35
+ * const clientManager = new ClientManager({ queryClient })
36
+ * await clientManager.initialize()
37
+ *
38
+ * const adapter = new CandidAdapter({ clientManager })
39
+ *
40
+ * // Optionally load the local parser for faster processing
41
+ * await adapter.loadParser()
42
+ *
43
+ * // Get the Candid definition for a canister
44
+ * const { idlFactory } = await adapter.getCandidDefinition("ryjl3-tyaaa-aaaaa-aaaba-cai")
45
+ * ```
46
+ */
47
+ export class CandidAdapter {
48
+ /** The client manager providing agent and identity access. */
49
+ public clientManager: CandidClientManager
50
+
51
+ /** The canister ID of the didjs canister for remote Candid compilation. */
52
+ public didjsCanisterId: CanisterId
53
+
54
+ /** The optional local parser module. */
55
+ private parserModule?: ReactorParser
56
+
57
+ /** Whether parser auto-loading has been attempted. */
58
+ private parserLoadAttempted = false
59
+
60
+ /** Function to unsubscribe from identity updates. */
61
+ public unsubscribe: () => void = noop
62
+
63
+ /**
64
+ * Creates a new CandidAdapter instance.
65
+ *
66
+ * @param params - The adapter parameters.
67
+ */
68
+ constructor({ clientManager, didjsCanisterId }: CandidAdapterParameters) {
69
+ this.clientManager = clientManager
70
+ this.didjsCanisterId = didjsCanisterId || this.getDefaultDidJsId()
71
+
72
+ // Subscribe to identity changes to update didjs canister ID if needed
73
+ this.unsubscribe = clientManager.subscribe(() => {
74
+ if (!didjsCanisterId) {
75
+ this.didjsCanisterId = this.getDefaultDidJsId()
76
+ }
77
+ })
78
+ }
79
+
80
+ /**
81
+ * The HTTP agent from the client manager.
82
+ */
83
+ get agent(): HttpAgent {
84
+ return this.clientManager.agent
85
+ }
86
+
87
+ /**
88
+ * Whether the local parser is available.
89
+ */
90
+ get hasParser(): boolean {
91
+ return this.parserModule !== undefined
92
+ }
93
+
94
+ /**
95
+ * Loads the local parser module for converting Candid to JavaScript.
96
+ * If no module is provided, attempts to dynamically load @ic-reactor/parser.
97
+ *
98
+ * @param module - Optional parser module to use.
99
+ * @throws Error if the parser loading fails.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * // Load the default parser
104
+ * await adapter.loadParser()
105
+ *
106
+ * // Or provide a custom parser
107
+ * import * as parser from "@ic-reactor/parser"
108
+ * await adapter.loadParser(parser)
109
+ * ```
110
+ */
111
+ public async loadParser(module?: ReactorParser): Promise<void> {
112
+ if (module !== undefined) {
113
+ this.parserModule = module
114
+ this.parserLoadAttempted = true
115
+ return
116
+ }
117
+
118
+ if (this.parserLoadAttempted) {
119
+ return // Already tried loading
120
+ }
121
+
122
+ this.parserLoadAttempted = true
123
+
124
+ try {
125
+ this.parserModule = require("@ic-reactor/parser")
126
+ if (this.parserModule?.default) {
127
+ await this.parserModule.default()
128
+ }
129
+ } catch (error) {
130
+ throw new Error(`Error loading parser: ${error}`)
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Attempts to load the parser silently (no error if not available).
136
+ * Useful for optional parser initialization.
137
+ */
138
+ private async tryLoadParser(): Promise<void> {
139
+ if (this.parserModule || this.parserLoadAttempted) {
140
+ return
141
+ }
142
+
143
+ this.parserLoadAttempted = true
144
+
145
+ try {
146
+ this.parserModule = require("@ic-reactor/parser")
147
+ if (this.parserModule?.default) {
148
+ await this.parserModule.default()
149
+ }
150
+ } catch {
151
+ // Silently fail - parser is optional
152
+ this.parserModule = undefined
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Gets the default didjs canister ID based on whether the agent is local or not.
158
+ */
159
+ private getDefaultDidJsId(): string {
160
+ return this.clientManager.isLocal
161
+ ? DEFAULT_LOCAL_DIDJS_ID
162
+ : DEFAULT_IC_DIDJS_ID
163
+ }
164
+
165
+ // ═══════════════════════════════════════════════════════════════════════════
166
+ // MAIN API - High-level methods for fetching Candid definitions
167
+ // ═══════════════════════════════════════════════════════════════════════════
168
+
169
+ /**
170
+ * Gets the parsed Candid definition for a canister, ready for use with Actor.createActor.
171
+ * This is the main entry point for fetching a canister's interface.
172
+ *
173
+ * @param canisterId - The canister ID to get the Candid definition for.
174
+ * @returns The parsed Candid definition with idlFactory and optional init.
175
+ * @throws Error if fetching or parsing fails.
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * const { idlFactory } = await adapter.getCandidDefinition("ryjl3-tyaaa-aaaaa-aaaba-cai")
180
+ * ```
181
+ */
182
+ public async getCandidDefinition(
183
+ canisterId: CanisterId
184
+ ): Promise<CandidDefinition> {
185
+ try {
186
+ const candidSource = await this.fetchCandidSource(canisterId)
187
+ return await this.parseCandidSource(candidSource)
188
+ } catch (error) {
189
+ throw new Error(`Error fetching canister ${canisterId}: ${error}`)
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Fetches the raw Candid source string for a canister.
195
+ * First attempts to get it from metadata, then falls back to the tmp hack method.
196
+ *
197
+ * @param canisterId - The canister ID to fetch the Candid source for.
198
+ * @returns The raw Candid source string (.did file contents).
199
+ * @throws Error if both methods fail.
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const candidSource = await adapter.fetchCandidSource("ryjl3-tyaaa-aaaaa-aaaba-cai")
204
+ * console.log(candidSource) // service { greet: (text) -> (text) query; }
205
+ * ```
206
+ */
207
+ public async fetchCandidSource(canisterId: CanisterId): Promise<string> {
208
+ // First attempt: Try getting Candid from metadata
209
+ const fromMetadata = await this.fetchFromMetadata(canisterId).catch(
210
+ () => undefined
211
+ )
212
+
213
+ if (fromMetadata) {
214
+ return fromMetadata
215
+ }
216
+
217
+ // Second attempt: Try the temporary hack method
218
+ const fromTmpHack = await this.fetchFromTmpHack(canisterId).catch(
219
+ () => undefined
220
+ )
221
+
222
+ if (fromTmpHack) {
223
+ return fromTmpHack
224
+ }
225
+
226
+ throw new Error("Failed to retrieve Candid source by any method.")
227
+ }
228
+
229
+ /**
230
+ * Parses Candid source string and returns the definition with idlFactory.
231
+ * First attempts to use the local parser, then falls back to the remote didjs canister.
232
+ *
233
+ * @param candidSource - The raw Candid source string.
234
+ * @returns The parsed Candid definition.
235
+ * @throws Error if parsing fails.
236
+ */
237
+ public async parseCandidSource(
238
+ candidSource: string
239
+ ): Promise<CandidDefinition> {
240
+ // Try to auto-load parser if not already loaded
241
+ await this.tryLoadParser()
242
+
243
+ let compiledJs: string | undefined
244
+
245
+ // First attempt: Try local parser (faster, no network)
246
+ if (this.parserModule) {
247
+ try {
248
+ compiledJs = this.compileLocal(candidSource)
249
+ } catch {
250
+ // Fall through to remote compilation
251
+ }
252
+ }
253
+
254
+ // Second attempt: Try remote didjs canister
255
+ if (!compiledJs) {
256
+ compiledJs = await this.compileRemote(candidSource)
257
+ }
258
+
259
+ if (!compiledJs) {
260
+ throw new Error("Failed to compile Candid to JavaScript")
261
+ }
262
+
263
+ return importCandidDefinition(compiledJs)
264
+ }
265
+
266
+ // ═══════════════════════════════════════════════════════════════════════════
267
+ // FETCH METHODS - Low-level methods for fetching Candid source
268
+ // ═══════════════════════════════════════════════════════════════════════════
269
+
270
+ /**
271
+ * Fetches Candid source from the canister's metadata.
272
+ *
273
+ * @param canisterId - The canister ID to query.
274
+ * @returns The Candid source string, or undefined if not available.
275
+ */
276
+ public async fetchFromMetadata(
277
+ canisterId: CanisterId
278
+ ): Promise<string | undefined> {
279
+ const status = await CanisterStatus.request({
280
+ agent: this.agent,
281
+ canisterId: canisterId as Principal,
282
+ paths: ["candid"],
283
+ })
284
+
285
+ return status.get("candid") as string | undefined
286
+ }
287
+
288
+ /**
289
+ * Fetches Candid source using the temporary hack method.
290
+ * This calls the `__get_candid_interface_tmp_hack` query method on the canister.
291
+ *
292
+ * @param canisterId - The canister ID to query.
293
+ * @returns The Candid source string.
294
+ */
295
+ public async fetchFromTmpHack(canisterId: CanisterId): Promise<string> {
296
+ const canisterIdStr =
297
+ typeof canisterId === "string" ? canisterId : canisterId.toString()
298
+
299
+ // Use raw agent.query instead of Actor.createActor
300
+ const response = await this.agent.query(canisterIdStr, {
301
+ methodName: "__get_candid_interface_tmp_hack",
302
+ arg: IDL.encode([], []),
303
+ })
304
+
305
+ if ("reply" in response && response.reply) {
306
+ const [candidSource] = IDL.decode([IDL.Text], response.reply.arg) as [
307
+ string,
308
+ ]
309
+ return candidSource
310
+ }
311
+
312
+ throw new Error(`Query failed: ${JSON.stringify(response)}`)
313
+ }
314
+
315
+ // ═══════════════════════════════════════════════════════════════════════════
316
+ // COMPILE METHODS - Methods for compiling Candid to JavaScript
317
+ // ═══════════════════════════════════════════════════════════════════════════
318
+
319
+ /**
320
+ * Compiles Candid source to JavaScript using the local WASM parser.
321
+ *
322
+ * @param candidSource - The Candid source to compile.
323
+ * @returns The compiled JavaScript code.
324
+ * @throws Error if the parser is not loaded.
325
+ */
326
+ public compileLocal(candidSource: string): string {
327
+ if (!this.parserModule) {
328
+ throw new Error("Parser not loaded. Call loadParser() first.")
329
+ }
330
+
331
+ return this.parserModule.didToJs(candidSource)
332
+ }
333
+
334
+ /**
335
+ * Compiles Candid source to JavaScript using the remote didjs canister.
336
+ *
337
+ * @param candidSource - The Candid source to compile.
338
+ * @param didjsCanisterId - Optional custom didjs canister ID.
339
+ * @returns The compiled JavaScript code, or undefined if compilation fails.
340
+ */
341
+ public async compileRemote(
342
+ candidSource: string,
343
+ didjsCanisterId?: string
344
+ ): Promise<string | undefined> {
345
+ const canisterId = didjsCanisterId || this.didjsCanisterId
346
+
347
+ // Use raw agent.query instead of Actor.createActor
348
+ const response = await this.agent.query(canisterId, {
349
+ methodName: "did_to_js",
350
+ arg: IDL.encode([IDL.Text], [candidSource]),
351
+ })
352
+
353
+ if ("reply" in response && response.reply) {
354
+ const [result] = IDL.decode([IDL.Opt(IDL.Text)], response.reply.arg) as [
355
+ [string] | [],
356
+ ]
357
+ return result[0]
358
+ }
359
+
360
+ throw new Error(`Query failed: ${JSON.stringify(response)}`)
361
+ }
362
+
363
+ /**
364
+ * Validates Candid source using the local parser.
365
+ *
366
+ * @param candidSource - The Candid source to validate.
367
+ * @returns True if the source is valid, false otherwise.
368
+ * @throws Error if the parser is not loaded.
369
+ */
370
+ public validateCandid(candidSource: string): boolean {
371
+ if (!this.parserModule) {
372
+ throw new Error("Parser not loaded. Call loadParser() first.")
373
+ }
374
+
375
+ return this.parserModule.validateIDL(candidSource)
376
+ }
377
+
378
+ // ═══════════════════════════════════════════════════════════════════════════
379
+ // DEPRECATED ALIASES - For backwards compatibility
380
+ // ═══════════════════════════════════════════════════════════════════════════
381
+
382
+ /**
383
+ * @deprecated Use `loadParser()` instead.
384
+ */
385
+ public async initializeParser(module?: ReactorParser): Promise<void> {
386
+ return this.loadParser(module)
387
+ }
388
+
389
+ /**
390
+ * @deprecated Use `fetchCandidSource()` instead.
391
+ */
392
+ public async fetchCandidDefinition(canisterId: CanisterId): Promise<string> {
393
+ return this.fetchCandidSource(canisterId)
394
+ }
395
+
396
+ /**
397
+ * @deprecated Use `fetchFromMetadata()` instead.
398
+ */
399
+ public async getFromMetadata(
400
+ canisterId: CanisterId
401
+ ): Promise<string | undefined> {
402
+ return this.fetchFromMetadata(canisterId)
403
+ }
404
+
405
+ /**
406
+ * @deprecated Use `fetchFromTmpHack()` instead.
407
+ */
408
+ public async getFromTmpHack(canisterId: CanisterId): Promise<string> {
409
+ return this.fetchFromTmpHack(canisterId)
410
+ }
411
+
412
+ /**
413
+ * @deprecated Use `parseCandidSource()` instead.
414
+ */
415
+ public async evaluateCandidDefinition(
416
+ data: string
417
+ ): Promise<CandidDefinition> {
418
+ return this.parseCandidSource(data)
419
+ }
420
+
421
+ /**
422
+ * @deprecated Use `compileRemote()` instead.
423
+ */
424
+ public async fetchDidTojs(
425
+ candidSource: string,
426
+ didjsCanisterId?: string
427
+ ): Promise<string | undefined> {
428
+ return this.compileRemote(candidSource, didjsCanisterId)
429
+ }
430
+
431
+ /**
432
+ * @deprecated Use `compileLocal()` instead.
433
+ */
434
+ public parseDidToJs(candidSource: string): string {
435
+ return this.compileLocal(candidSource)
436
+ }
437
+
438
+ /**
439
+ * @deprecated Use `validateCandid()` instead.
440
+ */
441
+ public validateIDL(candidSource: string): boolean {
442
+ return this.validateCandid(candidSource)
443
+ }
444
+ }
445
+
446
+ const noop = () => {}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Default didjs canister ID for the IC mainnet.
3
+ * This canister is used to compile Candid to JavaScript.
4
+ */
5
+ export const DEFAULT_IC_DIDJS_ID = "a4gq6-oaaaa-aaaab-qaa4q-cai"
6
+
7
+ /**
8
+ * Default didjs canister ID for local development.
9
+ * This canister is used to compile Candid to JavaScript locally.
10
+ */
11
+ export const DEFAULT_LOCAL_DIDJS_ID = "bd3sg-teaaa-aaaaa-qaaba-cai"