@ic-reactor/core 2.0.0 → 3.0.0-beta.1

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 (123) hide show
  1. package/dist/client.d.ts +161 -0
  2. package/dist/client.d.ts.map +1 -0
  3. package/dist/client.js +499 -0
  4. package/dist/client.js.map +1 -0
  5. package/dist/display/helper.d.ts +10 -0
  6. package/dist/display/helper.d.ts.map +1 -0
  7. package/dist/display/helper.js +67 -0
  8. package/dist/display/helper.js.map +1 -0
  9. package/dist/display/index.d.ts +4 -0
  10. package/dist/display/index.d.ts.map +1 -0
  11. package/dist/display/index.js +4 -0
  12. package/dist/display/index.js.map +1 -0
  13. package/dist/display/types.d.ts +31 -0
  14. package/dist/display/types.d.ts.map +1 -0
  15. package/dist/display/types.js +2 -0
  16. package/dist/display/types.js.map +1 -0
  17. package/dist/display/visitor.d.ts +28 -0
  18. package/dist/display/visitor.d.ts.map +1 -0
  19. package/dist/display/visitor.js +318 -0
  20. package/dist/display/visitor.js.map +1 -0
  21. package/dist/display-reactor.d.ts +245 -0
  22. package/dist/display-reactor.d.ts.map +1 -0
  23. package/dist/display-reactor.js +331 -0
  24. package/dist/display-reactor.js.map +1 -0
  25. package/dist/errors/index.d.ts +118 -0
  26. package/dist/errors/index.d.ts.map +1 -0
  27. package/dist/errors/index.js +204 -0
  28. package/dist/errors/index.js.map +1 -0
  29. package/dist/index.d.ts +9 -8
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +9 -47
  32. package/dist/index.js.map +1 -0
  33. package/dist/reactor.d.ts +133 -0
  34. package/dist/reactor.d.ts.map +1 -0
  35. package/dist/reactor.js +325 -0
  36. package/dist/reactor.js.map +1 -0
  37. package/dist/types/client.d.ts +89 -0
  38. package/dist/types/client.d.ts.map +1 -0
  39. package/dist/types/client.js +2 -0
  40. package/dist/types/client.js.map +1 -0
  41. package/dist/types/index.d.ts +6 -0
  42. package/dist/types/index.d.ts.map +1 -0
  43. package/dist/types/index.js +6 -0
  44. package/dist/types/index.js.map +1 -0
  45. package/dist/types/reactor.d.ts +117 -0
  46. package/dist/types/reactor.d.ts.map +1 -0
  47. package/dist/types/reactor.js +2 -0
  48. package/dist/types/reactor.js.map +1 -0
  49. package/dist/types/result.d.ts +48 -0
  50. package/dist/types/result.d.ts.map +1 -0
  51. package/dist/types/result.js +2 -0
  52. package/dist/types/result.js.map +1 -0
  53. package/dist/types/transform.d.ts +7 -0
  54. package/dist/types/transform.d.ts.map +1 -0
  55. package/dist/types/transform.js +2 -0
  56. package/dist/types/transform.js.map +1 -0
  57. package/dist/types/variant.d.ts +18 -0
  58. package/dist/types/variant.d.ts.map +1 -0
  59. package/dist/types/variant.js +2 -0
  60. package/dist/types/variant.js.map +1 -0
  61. package/dist/utils/agent.d.ts +30 -1
  62. package/dist/utils/agent.d.ts.map +1 -0
  63. package/dist/utils/agent.js +118 -16
  64. package/dist/utils/agent.js.map +1 -0
  65. package/dist/utils/candid.d.ts +39 -1
  66. package/dist/utils/candid.d.ts.map +1 -0
  67. package/dist/utils/candid.js +76 -16
  68. package/dist/utils/candid.js.map +1 -0
  69. package/dist/utils/constants.d.ts +3 -4
  70. package/dist/utils/constants.d.ts.map +1 -0
  71. package/dist/utils/constants.js +7 -11
  72. package/dist/utils/constants.js.map +1 -0
  73. package/dist/utils/helper.d.ts +16 -39
  74. package/dist/utils/helper.d.ts.map +1 -0
  75. package/dist/utils/helper.js +53 -155
  76. package/dist/utils/helper.js.map +1 -0
  77. package/dist/utils/index.d.ts +4 -5
  78. package/dist/utils/index.d.ts.map +1 -0
  79. package/dist/utils/index.js +5 -49
  80. package/dist/utils/index.js.map +1 -0
  81. package/dist/utils/polling.d.ts +176 -0
  82. package/dist/utils/polling.d.ts.map +1 -0
  83. package/dist/utils/polling.js +170 -0
  84. package/dist/utils/polling.js.map +1 -0
  85. package/dist/version.d.ts +5 -0
  86. package/dist/version.d.ts.map +1 -0
  87. package/dist/version.js +5 -0
  88. package/dist/version.js.map +1 -0
  89. package/package.json +65 -39
  90. package/LICENSE.md +0 -8
  91. package/README.md +0 -283
  92. package/dist/classes/actor/index.d.ts +0 -34
  93. package/dist/classes/actor/index.js +0 -245
  94. package/dist/classes/actor/types.d.ts +0 -113
  95. package/dist/classes/actor/types.js +0 -2
  96. package/dist/classes/adapter/index.d.ts +0 -19
  97. package/dist/classes/adapter/index.js +0 -140
  98. package/dist/classes/adapter/types.d.ts +0 -14
  99. package/dist/classes/adapter/types.js +0 -2
  100. package/dist/classes/agent/index.d.ts +0 -36
  101. package/dist/classes/agent/index.js +0 -218
  102. package/dist/classes/agent/types.d.ts +0 -87
  103. package/dist/classes/agent/types.js +0 -2
  104. package/dist/classes/index.d.ts +0 -3
  105. package/dist/classes/index.js +0 -19
  106. package/dist/classes/types.d.ts +0 -15
  107. package/dist/classes/types.js +0 -20
  108. package/dist/createActorManager.d.ts +0 -12
  109. package/dist/createActorManager.js +0 -17
  110. package/dist/createAgentManager.d.ts +0 -12
  111. package/dist/createAgentManager.js +0 -17
  112. package/dist/createCandidAdapter.d.ts +0 -11
  113. package/dist/createCandidAdapter.js +0 -16
  114. package/dist/createReactorCore.d.ts +0 -10
  115. package/dist/createReactorCore.js +0 -112
  116. package/dist/createReactorStore.d.ts +0 -11
  117. package/dist/createReactorStore.js +0 -31
  118. package/dist/types.d.ts +0 -96
  119. package/dist/types.js +0 -17
  120. package/dist/utils/hash.d.ts +0 -12
  121. package/dist/utils/hash.js +0 -70
  122. package/dist/utils/principal.d.ts +0 -1
  123. package/dist/utils/principal.js +0 -17
@@ -1,105 +1,38 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.stringToHash = exports.generateActorHash = exports.generateHash = exports.generateRequestHash = exports.jsonToString = exports.getProcessEnvNetwork = exports.isInLocalOrDevelopment = exports.importCandidDefinition = void 0;
4
- exports.noop = noop;
5
- exports.createStoreWithOptionalDevtools = createStoreWithOptionalDevtools;
6
- exports.getNetworkByHostname = getNetworkByHostname;
7
- exports.isQuery = isQuery;
8
- exports.createCompiledResult = createCompiledResult;
9
- exports.extractOkResult = extractOkResult;
10
- const sha2_1 = require("@noble/hashes/sha2");
11
- const utils_1 = require("@noble/hashes/utils");
12
- const middleware_1 = require("zustand/middleware");
13
- const zustand_1 = require("zustand");
14
- const hash_1 = require("./hash");
15
- const constants_1 = require("./constants");
16
- /**
17
- * No operation function that does nothing.
18
- * It can be used as a placeholder or for logging purposes.
19
- */
20
- function noop() {
21
- // eslint-disable-next-line no-console
22
- console.warn("No operation function called");
23
- }
24
- /**
25
- * Creates a Zustand store with optional DevTools middleware.
26
- *
27
- * @param initialState - The initial state of the store.
28
- * @param config - Configuration options for DevTools.
29
- * @returns A Zustand store with DevTools enabled if configured, otherwise a standard store.
30
- */
31
- function createStoreWithOptionalDevtools(initialState, config) {
32
- const createState = () => initialState;
33
- return (0, zustand_1.createStore)((0, middleware_1.subscribeWithSelector)((0, middleware_1.devtools)(createState, {
34
- enabled: !!config.withDevtools,
35
- serialize: {
36
- replacer: (_, value) => typeof value === "bigint" ? value.toString() : value,
37
- },
38
- ...config,
39
- })));
40
- }
41
- const importCandidDefinition = async (candidDef) => {
42
- if (typeof window === "undefined") {
43
- // Node.js environment - use dynamic evaluation
44
- try {
45
- const moduleExports = {};
46
- const moduleCode = candidDef.replace(/export const /g, "moduleExports.");
47
- const func = new Function("moduleExports", moduleCode);
48
- func(moduleExports);
49
- return moduleExports;
50
- }
51
- catch (error) {
52
- throw new Error(`Error importing candid definition in NodeJs: ${error.message}`);
53
- }
54
- }
55
- else {
56
- // Browser environment
57
- try {
58
- const loaderFunction = new Function(`
59
- const blob = new Blob([\`${candidDef}\`], { type: "application/javascript" })
60
- const url = URL.createObjectURL(blob)
61
- return import(url)
62
- `);
63
- return loaderFunction();
64
- }
65
- catch (error) {
66
- throw new Error(`Error importing candid definition: ${error}`);
67
- }
68
- }
1
+ import { LOCAL_HOSTS, REMOTE_HOSTS } from "./constants";
2
+ import { CanisterError } from "../errors";
3
+ export const generateKey = (args) => {
4
+ return JSON.stringify(args, (_, v) => typeof v === "bigint" ? v.toString() : v);
69
5
  };
70
- exports.importCandidDefinition = importCandidDefinition;
71
6
  /**
72
7
  * Checks if the current environment is local or development.
73
8
  *
74
9
  * @returns `true` if running in a local or development environment, otherwise `false`.
75
10
  */
76
- const isInLocalOrDevelopment = () => {
11
+ export const isInLocalOrDevelopment = () => {
77
12
  return typeof process !== "undefined" && process.env.DFX_NETWORK === "local";
78
13
  };
79
- exports.isInLocalOrDevelopment = isInLocalOrDevelopment;
80
14
  /**
81
15
  * Retrieves the network from the process environment variables.
82
16
  *
83
17
  * @returns The network name, defaulting to "ic" if not specified.
84
18
  */
85
- const getProcessEnvNetwork = () => {
19
+ export const getProcessEnvNetwork = () => {
86
20
  if (typeof process === "undefined")
87
21
  return "ic";
88
22
  else
89
23
  return process.env.DFX_NETWORK ?? "ic";
90
24
  };
91
- exports.getProcessEnvNetwork = getProcessEnvNetwork;
92
25
  /**
93
26
  * Determines the network type based on the provided hostname.
94
27
  *
95
28
  * @param hostname - The hostname to evaluate.
96
29
  * @returns A string indicating the network type: "local", "remote", or "ic".
97
30
  */
98
- function getNetworkByHostname(hostname) {
99
- if (constants_1.LOCAL_HOSTS.some((host) => hostname.endsWith(host))) {
31
+ export function getNetworkByHostname(hostname) {
32
+ if (LOCAL_HOSTS.some((host) => hostname.endsWith(host))) {
100
33
  return "local";
101
34
  }
102
- else if (constants_1.REMOTE_HOSTS.some((host) => hostname.endsWith(host))) {
35
+ else if (REMOTE_HOSTS.some((host) => hostname.endsWith(host))) {
103
36
  return "remote";
104
37
  }
105
38
  else {
@@ -107,92 +40,57 @@ function getNetworkByHostname(hostname) {
107
40
  }
108
41
  }
109
42
  /**
110
- * Checks if a given IDL function is a query.
111
- *
112
- * @param func - The IDL function to check.
113
- * @returns `true` if the function is a query or composite query, otherwise `false`.
114
- */
115
- function isQuery(func) {
116
- return (func.annotations.includes("query") ||
117
- func.annotations.includes("composite_query"));
118
- }
119
- const jsonToString = (json, space = 2) => {
120
- return JSON.stringify(json, (_, value) => (typeof value === "bigint" ? `BigInt(${value})` : value), space);
121
- };
122
- exports.jsonToString = jsonToString;
123
- const generateRequestHash = (args = []) => {
124
- const serializedArgs = (0, hash_1.createSimpleHash)(args);
125
- return `0x${serializedArgs}`;
126
- };
127
- exports.generateRequestHash = generateRequestHash;
128
- const generateHash = (field) => {
129
- const serializedArgs = JSON.stringify(field);
130
- return (0, exports.stringToHash)(serializedArgs ?? "");
131
- };
132
- exports.generateHash = generateHash;
133
- const generateActorHash = (actor) => {
134
- const serializedArgs = JSON.stringify(actor);
135
- return (0, exports.stringToHash)(serializedArgs ?? "");
136
- };
137
- exports.generateActorHash = generateActorHash;
138
- const stringToHash = (str) => {
139
- const hashBytes = (0, sha2_1.sha256)(str);
140
- return `0x${(0, utils_1.bytesToHex)(hashBytes)}`;
141
- };
142
- exports.stringToHash = stringToHash;
143
- /**
144
- * Helper function for extracting the value from a compiled result { Ok: T } or { Err: E }
43
+ * Helper function for extracting the value from a compiled result { Ok: T } or throw a CanisterError if { Err: E }
44
+ * Supports both uppercase (Ok/Err - Rust) and lowercase (ok/err - Motoko) conventions.
145
45
  *
146
46
  * @param result - The compiled result to extract from.
147
- * @returns A `CompiledResult` object indicating success or failure.
47
+ * @returns The extracted value from the compiled result.
48
+ * @throws CanisterError with the typed error value if result is { Err: E } or { err: E }
148
49
  */
149
- function createCompiledResult(result) {
150
- if (result && typeof result === "object" && "Ok" in result) {
151
- return {
152
- isOk: true,
153
- isErr: false,
154
- value: result.Ok,
155
- error: null,
156
- };
50
+ export function extractOkResult(result) {
51
+ if (!result || typeof result !== "object") {
52
+ // Non-object, return as-is
53
+ return result;
157
54
  }
158
- else if (result && typeof result === "object" && "Err" in result) {
159
- return {
160
- isOk: false,
161
- isErr: true,
162
- value: null,
163
- error: result.Err,
164
- };
55
+ // Handle { Ok: T } (Rust convention)
56
+ if ("Ok" in result) {
57
+ return result.Ok;
165
58
  }
166
- else if (result) {
167
- // For non-Result types
168
- return {
169
- isOk: true,
170
- isErr: false,
171
- value: result,
172
- error: null,
173
- };
59
+ // Handle { ok: T } (Motoko convention)
60
+ if ("ok" in result) {
61
+ return result.ok;
174
62
  }
175
- else {
176
- // For non-Result types
177
- return {
178
- isOk: false,
179
- isErr: false,
180
- value: undefined,
181
- error: null,
182
- };
63
+ // Handle { Err: E } (Rust convention) - throw CanisterError
64
+ if ("Err" in result) {
65
+ throw new CanisterError(result.Err);
66
+ }
67
+ // Handle { err: E } (Motoko convention) - throw CanisterError
68
+ if ("err" in result) {
69
+ throw new CanisterError(result.err);
183
70
  }
71
+ // Non-Result type, return as-is
72
+ return result;
184
73
  }
74
+ export const isNullish = (value) => value === null || value === undefined;
75
+ export const nonNullish = (value) => value !== null && value !== undefined;
76
+ export const uint8ArrayToHex = (bytes) => {
77
+ const hex = Array.from(bytes)
78
+ .map((b) => b.toString(16).padStart(2, "0"))
79
+ .join("");
80
+ return `0x${hex}`;
81
+ };
82
+ export const hexToUint8Array = (hex) => {
83
+ if (hex.startsWith("0x")) {
84
+ hex = hex.slice(2);
85
+ }
86
+ return new Uint8Array(hex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || []);
87
+ };
185
88
  /**
186
- * Helper function for extracting the value from a compiled result { Ok: T } or throw the error if { Err: E }
187
- *
188
- * @param result - The compiled result to extract from.
189
- * @returns The extracted value from the compiled result.
190
- * @throws The error from the compiled result.
89
+ * Converts a JSON-serializable value to a string, handling BigInt values.
90
+ * @param value - The value to convert
91
+ * @returns A string representation of the value
191
92
  */
192
- function extractOkResult(result) {
193
- const compiledResult = createCompiledResult(result);
194
- if (compiledResult.isErr) {
195
- throw compiledResult.error;
196
- }
197
- return compiledResult.value;
198
- }
93
+ export const jsonToString = (value) => {
94
+ return JSON.stringify(value, (_, v) => (typeof v === "bigint" ? v.toString() : v), 2);
95
+ };
96
+ //# sourceMappingURL=helper.js.map
@@ -0,0 +1 @@
1
+ {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CAAC,CAAA;IACX,OAAO,KAAK,GAAG,EAAE,CAAA;AACnB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAW,EAA2B,EAAE;IACtE,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACzB,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACpB,CAAC;IACD,OAAO,IAAI,UAAU,CACnB,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAC9D,CAAA;AACH,CAAC,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAAU,EAAU,EAAE;IACjD,OAAO,IAAI,CAAC,SAAS,CACnB,KAAK,EACL,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EACpD,CAAC,CACF,CAAA;AACH,CAAC,CAAA"}
@@ -1,6 +1,5 @@
1
- export * from "./helper";
1
+ export * from "./candid";
2
2
  export * from "./constants";
3
- export * from "./hash";
4
- export * as candid from "./candid";
5
- export * as principal from "./principal";
6
- export * as agent from "./agent";
3
+ export * from "./helper";
4
+ export * from "./polling";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA"}
@@ -1,49 +1,5 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
19
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
20
- };
21
- var __importStar = (this && this.__importStar) || (function () {
22
- var ownKeys = function(o) {
23
- ownKeys = Object.getOwnPropertyNames || function (o) {
24
- var ar = [];
25
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
- return ar;
27
- };
28
- return ownKeys(o);
29
- };
30
- return function (mod) {
31
- if (mod && mod.__esModule) return mod;
32
- var result = {};
33
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
- __setModuleDefault(result, mod);
35
- return result;
36
- };
37
- })();
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.agent = exports.principal = exports.candid = void 0;
40
- __exportStar(require("./helper"), exports);
41
- __exportStar(require("./constants"), exports);
42
- __exportStar(require("./hash"), exports);
43
- // Re-export the peerDependencies
44
- /// https://agent-js.icp.xyz/candid
45
- exports.candid = __importStar(require("./candid"));
46
- /// https://agent-js.icp.xyz/principal
47
- exports.principal = __importStar(require("./principal"));
48
- /// https://agent-js.icp.xyz/agent
49
- exports.agent = __importStar(require("./agent"));
1
+ export * from "./candid";
2
+ export * from "./constants";
3
+ export * from "./helper";
4
+ export * from "./polling";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA"}
@@ -0,0 +1,176 @@
1
+ /**
2
+ * @module polling
3
+ * @description
4
+ * Polling strategy for Internet Computer (Dfinity) agent update calls.
5
+ *
6
+ * This module provides a configurable, intelligent polling mechanism that:
7
+ * - Starts with rapid polling for quick responses (fast phase)
8
+ * - Gradually increases delay intervals (ramp phase)
9
+ * - Settles into steady-state polling (plateau phase)
10
+ * - Adds jitter to prevent thundering herd problems
11
+ * - Provides structured logging with elapsed time and status
12
+ * - Supports graceful cancellation via AbortSignal
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * const strategy = createPollingStrategy({
17
+ * context: "signer-creation",
18
+ * fastAttempts: 10,
19
+ * plateauDelayMs: 5000
20
+ * });
21
+ *
22
+ * const result = await actor.createSigner(params, {
23
+ * pollingOptions: { strategy }
24
+ * });
25
+ * ```
26
+ */
27
+ import { PollStrategy } from "@icp-sdk/core/agent";
28
+ export interface PollingConfig {
29
+ /**
30
+ * Logical operation name used in log messages for identifying the polling context.
31
+ *
32
+ * Used to distinguish between different polling operations in console output.
33
+ * Choose descriptive names that help with debugging and monitoring.
34
+ *
35
+ * @default "operation"
36
+ * @example "sign-transaction", "document-upload"
37
+ */
38
+ context?: string;
39
+ /**
40
+ * Custom prefix prepended to all log messages from this polling strategy.
41
+ *
42
+ * Allows filtering and identifying logs specific to this polling instance.
43
+ * Useful when running multiple polling operations concurrently.
44
+ *
45
+ * @default "[Polling]"
46
+ * @example "[PaymentPolling]", "[TransactionPolling]", "[SignerPolling]"
47
+ */
48
+ logPrefix?: string;
49
+ /**
50
+ * Number of initial rapid polling attempts before transitioning to ramp phase.
51
+ *
52
+ * During fast phase, polls occur at `fastDelayMs` intervals (plus jitter).
53
+ * Higher values = more aggressive initial polling for fast responses.
54
+ * Lower values = faster transition to exponential backoff.
55
+ *
56
+ * @default 10
57
+ * @example 5 (for slower operations), 15 (for very fast operations)
58
+ */
59
+ fastAttempts?: number;
60
+ /**
61
+ * Base delay in milliseconds between polls during the fast phase.
62
+ *
63
+ * This is the baseline interval before jitter is applied.
64
+ * Actual delay will vary by ±`jitterRatio` percentage.
65
+ * Lower values = more aggressive polling, higher network load.
66
+ *
67
+ * @default 100
68
+ * @example 50 (aggressive), 200 (conservative)
69
+ */
70
+ fastDelayMs?: number;
71
+ /**
72
+ * Duration threshold in milliseconds for the ramp phase.
73
+ *
74
+ * While elapsed time < rampUntilMs, delay grows exponentially from
75
+ * `fastDelayMs` up to `plateauDelayMs` using a power curve (0.7 exponent).
76
+ * After this duration, polling enters plateau phase with constant delays.
77
+ *
78
+ * @default 20000 (20 seconds)
79
+ * @example 10_000 (faster transition), 30_000 (longer ramp for slow ops)
80
+ */
81
+ rampUntilMs?: number;
82
+ /**
83
+ * Steady-state polling delay in milliseconds during plateau phase.
84
+ *
85
+ * Once ramp phase completes, all subsequent polls use this interval (plus jitter).
86
+ * This is the "cruise speed" for long-running operations.
87
+ * Balance between responsiveness and network/resource efficiency.
88
+ *
89
+ * @default 5000 (5 seconds)
90
+ * @example 2_000 (more responsive), 10_000 (more efficient)
91
+ */
92
+ plateauDelayMs?: number;
93
+ /**
94
+ * Randomization ratio (0-1) for adding jitter to prevent thundering herd.
95
+ *
96
+ * Jitter adds ±(ratio * delay) randomness to each polling interval.
97
+ * Higher values = more randomization, better distribution across time.
98
+ * Lower values = more predictable intervals, less variance.
99
+ * Prevents synchronized polling when multiple clients start simultaneously.
100
+ *
101
+ * @default 0.4 (±40% randomization)
102
+ * @example 0.2 (±20%, less jitter), 0.5 (±50%, more jitter)
103
+ */
104
+ jitterRatio?: number;
105
+ /**
106
+ * Maximum time in milliseconds between log outputs (heartbeat interval).
107
+ *
108
+ * Forces a log message if this much time passes without logging,
109
+ * even if normal log throttling would suppress it.
110
+ * Prevents "silent" long-running operations; ensures monitoring visibility.
111
+ *
112
+ * @default 15000 (15 seconds)
113
+ * @example 10_000 (more frequent heartbeats), 30_000 (less verbose)
114
+ */
115
+ maxLogIntervalMs?: number;
116
+ /**
117
+ * External abort signal for graceful cancellation of polling operation.
118
+ *
119
+ * When the signal is aborted, the polling strategy throws an error
120
+ * on the next poll attempt. Use AbortController to create signals.
121
+ * Allows coordinated cancellation across multiple async operations.
122
+ *
123
+ * @default undefined (no external cancellation)
124
+ * @example
125
+ * ```typescript
126
+ * const controller = new AbortController();
127
+ * const strategy = createPollingStrategy({
128
+ * abortSignal: controller.signal
129
+ * });
130
+ * // Later: controller.abort();
131
+ * ```
132
+ */
133
+ abortSignal?: AbortSignal;
134
+ }
135
+ /**
136
+ * Creates an polling strategy for Internet Computer agent update calls.
137
+ *
138
+ * The strategy implements three phases:
139
+ * 1. **Fast Phase**: Initial rapid polling (default: 10 attempts @ 100ms intervals)
140
+ * 2. **Ramp Phase**: Exponential backoff growth (default: up to 20s elapsed)
141
+ * 3. **Plateau Phase**: Steady-state polling (default: 5s intervals)
142
+ *
143
+ * The strategy continues polling while request status is RECEIVED/PROCESSING,
144
+ * and only terminates on REPLIED/REJECTED/DONE status or when aborted.
145
+ *
146
+ * @param {PollingConfig} [cfg={}] - Configuration options
147
+ * @returns {PollStrategy} - Async strategy function compatible with agent pollingOptions.strategy
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * // Basic usage
152
+ * const strategy = createPollingStrategy();
153
+ *
154
+ * // Custom configuration for long-running operations
155
+ * const strategy = createPollingStrategy({
156
+ * context: "blockchain-sync",
157
+ * fastAttempts: 5,
158
+ * fastDelayMs: 200,
159
+ * rampUntilMs: 30_000,
160
+ * plateauDelayMs: 10_000,
161
+ * jitterRatio: 0.3
162
+ * });
163
+ *
164
+ * // With abort signal
165
+ * const controller = new AbortController();
166
+ * const strategy = createPollingStrategy({
167
+ * context: "transaction-signing",
168
+ * abortSignal: controller.signal
169
+ * });
170
+ * // Later: controller.abort();
171
+ * ```
172
+ *
173
+ * @throws {Error} When abortSignal is triggered during polling
174
+ */
175
+ export declare function createPollingStrategy(cfg?: PollingConfig): PollStrategy;
176
+ //# sourceMappingURL=polling.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"polling.d.ts","sourceRoot":"","sources":["../../src/utils/polling.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EACL,YAAY,EAGb,MAAM,qBAAqB,CAAA;AAG5B,MAAM,WAAW,aAAa;IAC5B;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAEhB;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAElB;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IAErB;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;;;;;;;;OASG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB;;;;;;;;;;OAUG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IAEzB;;;;;;;;;;;;;;;;OAgBG;IACH,WAAW,CAAC,EAAE,WAAW,CAAA;CAC1B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,GAAE,aAAkB,GAAG,YAAY,CA2I3E"}