@arkiv-network/sdk 0.7.0 → 0.8.0-dev.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 (210) hide show
  1. package/README.md +29 -16
  2. package/dist/attr/index.cjs +34 -0
  3. package/dist/attr/index.d.cts +2 -0
  4. package/dist/attr/index.d.ts +2 -0
  5. package/dist/attr/index.js +3 -0
  6. package/dist/attr-BDZ-APg5.js +809 -0
  7. package/dist/attr-BDZ-APg5.js.map +1 -0
  8. package/dist/attr-BvxHN99W.cjs +1029 -0
  9. package/dist/chains/index.cjs +2 -3
  10. package/dist/chains/index.d.cts +39 -77
  11. package/dist/chains/index.d.cts.map +1 -1
  12. package/dist/chains/index.d.ts +22 -60
  13. package/dist/chains/index.d.ts.map +1 -1
  14. package/dist/chains/index.js +2 -2
  15. package/dist/chains-BJrZs6sG.js +57 -0
  16. package/dist/chains-BJrZs6sG.js.map +1 -0
  17. package/dist/chains-BYRTTipa.cjs +73 -0
  18. package/dist/changeOwnership-B7bEgla4.d.cts +509 -0
  19. package/dist/changeOwnership-B7bEgla4.d.cts.map +1 -0
  20. package/dist/changeOwnership-DwgtdSFc.d.ts +509 -0
  21. package/dist/changeOwnership-DwgtdSFc.d.ts.map +1 -0
  22. package/dist/entity/index.cjs +19 -0
  23. package/dist/entity/index.d.cts +4 -0
  24. package/dist/entity/index.d.ts +4 -0
  25. package/dist/entity/index.js +6 -0
  26. package/dist/entity-B0t6sN7F.cjs +71 -0
  27. package/dist/entity-BIp_df9u.js +67 -0
  28. package/dist/entity-BIp_df9u.js.map +1 -0
  29. package/dist/entity-CFhbAv0R.js +70 -0
  30. package/dist/entity-CFhbAv0R.js.map +1 -0
  31. package/dist/entity-wfBnZd91.cjs +98 -0
  32. package/dist/errors-D-eJkGVc.cjs +56 -0
  33. package/dist/errors-DGB8AgT2.js +33 -0
  34. package/dist/errors-DGB8AgT2.js.map +1 -0
  35. package/dist/expiry-BUYIXTGb.cjs +135 -0
  36. package/dist/expiry-BxOlvVWC.d.ts +79 -0
  37. package/dist/expiry-BxOlvVWC.d.ts.map +1 -0
  38. package/dist/expiry-DGRzrSan.js +95 -0
  39. package/dist/expiry-DGRzrSan.js.map +1 -0
  40. package/dist/expiry-DRV29F1r.d.cts +79 -0
  41. package/dist/expiry-DRV29F1r.d.cts.map +1 -0
  42. package/dist/flags-0Vl5rrHq.d.cts +41 -0
  43. package/dist/flags-0Vl5rrHq.d.cts.map +1 -0
  44. package/dist/flags-Ct8k0gpB.cjs +43 -0
  45. package/dist/flags-ZtlvOIIk.js +33 -0
  46. package/dist/flags-ZtlvOIIk.js.map +1 -0
  47. package/dist/flags-wmcMoAnN.d.ts +41 -0
  48. package/dist/flags-wmcMoAnN.d.ts.map +1 -0
  49. package/dist/index-Cgw1u5aY.d.cts +278 -0
  50. package/dist/index-Cgw1u5aY.d.cts.map +1 -0
  51. package/dist/index-ClgIuxJ8.d.ts +159 -0
  52. package/dist/index-ClgIuxJ8.d.ts.map +1 -0
  53. package/dist/index-D0CmtiWT.d.cts +159 -0
  54. package/dist/index-D0CmtiWT.d.cts.map +1 -0
  55. package/dist/index-D8LZt-3J.d.cts +417 -0
  56. package/dist/index-D8LZt-3J.d.cts.map +1 -0
  57. package/dist/index-DVYFaXNV.d.ts +417 -0
  58. package/dist/index-DVYFaXNV.d.ts.map +1 -0
  59. package/dist/index-VCqgn29D.d.ts +278 -0
  60. package/dist/index-VCqgn29D.d.ts.map +1 -0
  61. package/dist/index.cjs +675 -357
  62. package/dist/index.d.cts +251 -203
  63. package/dist/index.d.cts.map +1 -1
  64. package/dist/index.d.ts +251 -203
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +626 -355
  67. package/dist/index.js.map +1 -1
  68. package/dist/payload-Bnw1hrvb.cjs +83 -0
  69. package/dist/payload-CIxSn_DW.js +67 -0
  70. package/dist/payload-CIxSn_DW.js.map +1 -0
  71. package/dist/payload-Dgx3PQeK.d.ts +94 -0
  72. package/dist/payload-Dgx3PQeK.d.ts.map +1 -0
  73. package/dist/payload-P0nWyjLg.d.cts +94 -0
  74. package/dist/payload-P0nWyjLg.d.cts.map +1 -0
  75. package/dist/query/index.cjs +24 -149
  76. package/dist/query/index.d.cts +5 -3
  77. package/dist/query/index.d.ts +5 -3
  78. package/dist/query/index.js +6 -137
  79. package/dist/queryBuilder-BXDvX1K_.cjs +1123 -0
  80. package/dist/queryBuilder-CbLL4pG5.js +963 -0
  81. package/dist/queryBuilder-CbLL4pG5.js.map +1 -0
  82. package/dist/selection-BvK6yX0g.d.cts +433 -0
  83. package/dist/selection-BvK6yX0g.d.cts.map +1 -0
  84. package/dist/selection-fpmI3ADQ.d.ts +433 -0
  85. package/dist/selection-fpmI3ADQ.d.ts.map +1 -0
  86. package/dist/types/index.cjs +4 -1
  87. package/dist/types/index.d.cts +7 -2
  88. package/dist/types/index.d.ts +7 -2
  89. package/dist/types/index.js +4 -1
  90. package/dist/utils/index.cjs +4 -17
  91. package/dist/utils/index.d.cts +3 -17
  92. package/dist/utils/index.d.ts +3 -17
  93. package/dist/utils/index.js +4 -18
  94. package/package.json +26 -5
  95. package/src/actions/public/getEntity.ts +27 -43
  96. package/src/actions/public/getEntityNonce.ts +30 -0
  97. package/src/actions/public/predictEntityKeys.test.ts +143 -0
  98. package/src/actions/public/predictEntityKeys.ts +138 -0
  99. package/src/actions/public/query.ts +33 -69
  100. package/src/actions/public/watchEntityEvents.test.ts +414 -0
  101. package/src/actions/public/watchEntityEvents.ts +225 -0
  102. package/src/actions/wallet/changeOwnership.ts +8 -8
  103. package/src/actions/wallet/createEntity.ts +104 -26
  104. package/src/actions/wallet/deleteEntity.ts +2 -3
  105. package/src/actions/wallet/extendEntity.ts +39 -16
  106. package/src/actions/wallet/mutateEntities.test.ts +76 -0
  107. package/src/actions/wallet/mutateEntities.ts +29 -74
  108. package/src/actions/wallet/patchEntity.ts +90 -0
  109. package/src/attr/attributes.test.ts +120 -0
  110. package/src/attr/attributes.ts +190 -0
  111. package/src/attr/codec.test.ts +162 -0
  112. package/src/attr/codec.ts +220 -0
  113. package/src/attr/decimal.ts +86 -0
  114. package/src/attr/errors.ts +145 -0
  115. package/src/attr/index.ts +50 -0
  116. package/src/attr/names.ts +106 -0
  117. package/src/attr/types.ts +150 -0
  118. package/src/attr/values.test.ts +271 -0
  119. package/src/attr/values.ts +502 -0
  120. package/src/chains/cheesecake.ts +22 -0
  121. package/src/chains/index.ts +1 -2
  122. package/src/clients/createPublicClient.test.ts +3 -5
  123. package/src/clients/createPublicClient.ts +5 -4
  124. package/src/clients/createWalletClient.test.ts +2 -2
  125. package/src/clients/createWalletClient.ts +13 -7
  126. package/src/clients/decorators/arkivPublic.ts +160 -139
  127. package/src/clients/decorators/arkivWallet.ts +91 -95
  128. package/src/consts.ts +2 -1
  129. package/src/entity/create.test.ts +184 -0
  130. package/src/entity/errors.ts +38 -0
  131. package/src/entity/events.ts +16 -0
  132. package/src/entity/expiry.test.ts +195 -0
  133. package/src/entity/expiry.ts +181 -0
  134. package/src/entity/flags.ts +65 -0
  135. package/src/entity/index.ts +14 -0
  136. package/src/entity/key.ts +68 -0
  137. package/src/entity/operations.ts +134 -0
  138. package/src/entity/params.ts +15 -0
  139. package/src/errors.ts +33 -28
  140. package/src/index.ts +6 -0
  141. package/src/query/engine.ts +59 -134
  142. package/src/query/errors.ts +151 -0
  143. package/src/query/expression.test.ts +286 -0
  144. package/src/query/expression.ts +493 -0
  145. package/src/query/index.ts +40 -4
  146. package/src/query/injection.test.ts +151 -0
  147. package/src/query/queryBuilder.test.ts +322 -637
  148. package/src/query/queryBuilder.ts +126 -359
  149. package/src/query/queryResult.ts +54 -51
  150. package/src/query/selection.test.ts +48 -98
  151. package/src/query/selection.ts +77 -65
  152. package/src/types/entity.test.ts +44 -155
  153. package/src/types/entity.ts +62 -44
  154. package/src/types/events.ts +64 -23
  155. package/src/types/index.ts +20 -16
  156. package/src/types/rpcSchema.ts +70 -33
  157. package/src/utils/arkivTransactions.test.ts +681 -38
  158. package/src/utils/arkivTransactions.ts +249 -104
  159. package/src/utils/chains.test.ts +21 -24
  160. package/src/utils/compression.ts +1 -1
  161. package/src/utils/entities.test.ts +62 -0
  162. package/src/utils/entities.ts +111 -29
  163. package/src/utils/expirationTime.ts +114 -10
  164. package/src/utils/logger.ts +2 -2
  165. package/src/utils/payload.ts +4 -2
  166. package/src/utils/revert.test.ts +99 -0
  167. package/src/utils/revert.ts +145 -0
  168. package/dist/chains-BifaY04V.cjs +0 -108
  169. package/dist/chains-CrtkVbBh.js +0 -86
  170. package/dist/chains-CrtkVbBh.js.map +0 -1
  171. package/dist/consts-AUoL-v42.cjs +0 -18
  172. package/dist/consts-BV4PR-de.js +0 -7
  173. package/dist/consts-BV4PR-de.js.map +0 -1
  174. package/dist/entity-B6g_EPm1.d.cts +0 -382
  175. package/dist/entity-B6g_EPm1.d.cts.map +0 -1
  176. package/dist/entity-qoLMAuuk.d.ts +0 -382
  177. package/dist/entity-qoLMAuuk.d.ts.map +0 -1
  178. package/dist/index-DdspxNAA.d.ts +0 -481
  179. package/dist/index-DdspxNAA.d.ts.map +0 -1
  180. package/dist/index-Ds9dwqb5.d.cts +0 -481
  181. package/dist/index-Ds9dwqb5.d.cts.map +0 -1
  182. package/dist/payload-B2kFJyah.d.ts +0 -6
  183. package/dist/payload-B2kFJyah.d.ts.map +0 -1
  184. package/dist/payload-CJN8fTvX.d.cts +0 -6
  185. package/dist/payload-CJN8fTvX.d.cts.map +0 -1
  186. package/dist/payload-Claf2jUO.js +0 -13
  187. package/dist/payload-Claf2jUO.js.map +0 -1
  188. package/dist/payload-DpA5PA-w.cjs +0 -23
  189. package/dist/query/index.js.map +0 -1
  190. package/dist/queryBuilder-D2uwP9jI.js +0 -704
  191. package/dist/queryBuilder-D2uwP9jI.js.map +0 -1
  192. package/dist/queryBuilder-UW2MCaX4.cjs +0 -792
  193. package/dist/utils/index.d.cts.map +0 -1
  194. package/dist/utils/index.d.ts.map +0 -1
  195. package/dist/utils/index.js.map +0 -1
  196. package/src/actions/public/buildQuery.ts +0 -10
  197. package/src/actions/public/subscribeEntityEvents.ts +0 -119
  198. package/src/actions/wallet/updateEntity.ts +0 -60
  199. package/src/chains/braga.ts +0 -26
  200. package/src/chains/kaolin.ts +0 -29
  201. package/src/query/engine.test.ts +0 -526
  202. package/src/query/predicate.test.ts +0 -461
  203. package/src/query/predicate.ts +0 -144
  204. package/src/query/queryResult.test.ts +0 -270
  205. package/src/query/selectQueryBuilder.test.ts +0 -210
  206. package/src/types/attributes.ts +0 -16
  207. package/src/utils/validation.test.ts +0 -60
  208. package/src/utils/validation.ts +0 -32
  209. /package/dist/{types-H-TSmRpm.js → types-Bx1EKe0v.js} +0 -0
  210. /package/dist/{types-o3zWarRp.cjs → types-CKPddlfS.cjs} +0 -0
@@ -1,792 +0,0 @@
1
- const require_consts = require('./consts-AUoL-v42.cjs');
2
- let viem = require("viem");
3
-
4
- //#region src/utils/logger.ts
5
- const ROOT_NAMESPACE = "arkiv";
6
- function getDebugEnv() {
7
- if (typeof process !== "undefined") {
8
- const debugEnv = process?.env?.DEBUG;
9
- if (debugEnv) return debugEnv;
10
- }
11
- if (typeof globalThis !== "undefined" && "localStorage" in globalThis) try {
12
- return globalThis.localStorage?.getItem("DEBUG") || "";
13
- } catch {}
14
- return "";
15
- }
16
- function matchesPattern(namespace, pattern) {
17
- if (pattern === namespace) return true;
18
- if (pattern.endsWith("*")) {
19
- const prefix = pattern.slice(0, -1);
20
- return namespace.startsWith(prefix);
21
- }
22
- if (pattern.startsWith("-")) return !matchesPattern(namespace, pattern.slice(1));
23
- return false;
24
- }
25
- function isEnabled(namespace) {
26
- const debugEnv = getDebugEnv();
27
- if (!debugEnv) return false;
28
- const patterns = debugEnv.split(/[\s,]+/).filter((p) => p.length > 0);
29
- if (patterns.length === 0) return false;
30
- let enabled = false;
31
- for (const pattern of patterns) if (pattern.startsWith("-")) {
32
- if (matchesPattern(namespace, pattern)) return false;
33
- } else if (matchesPattern(namespace, pattern)) enabled = true;
34
- return enabled;
35
- }
36
- const enabledNamespaces = /* @__PURE__ */ new Set();
37
- const disabledNamespaces = /* @__PURE__ */ new Set();
38
- const COLOR_PALETTE = [
39
- "#0000FF",
40
- "#008000",
41
- "#FF0000",
42
- "#FF00FF",
43
- "#FFA500",
44
- "#800080",
45
- "#00CED1",
46
- "#FF1493",
47
- "#32CD32",
48
- "#1E90FF",
49
- "#FF4500",
50
- "#9370DB",
51
- "#00FA9A",
52
- "#FFD700",
53
- "#DC143C",
54
- "#00BFFF",
55
- "#FF69B4",
56
- "#20B2AA",
57
- "#DA70D6",
58
- "#4682B4"
59
- ];
60
- const isNode = typeof process !== "undefined" && process.versions?.node != null;
61
- const ANSI_COLORS = [
62
- "\x1B[94m",
63
- "\x1B[92m",
64
- "\x1B[91m",
65
- "\x1B[95m",
66
- "\x1B[93m",
67
- "\x1B[96m",
68
- "\x1B[35m",
69
- "\x1B[36m",
70
- "\x1B[32m",
71
- "\x1B[34m",
72
- "\x1B[33m",
73
- "\x1B[31m",
74
- "\x1B[90m",
75
- "\x1B[37m",
76
- "\x1B[1m"
77
- ];
78
- const ANSI_RESET = "\x1B[0m";
79
- const ANSI_BOLD = "\x1B[1m";
80
- const namespaceColors = /* @__PURE__ */ new Map();
81
- function getColorForNamespace(namespace) {
82
- const cachedColor = namespaceColors.get(namespace);
83
- if (cachedColor) return cachedColor;
84
- let hash = 0;
85
- for (let i = 0; i < namespace.length; i++) {
86
- const char = namespace.charCodeAt(i);
87
- hash = (hash << 5) - hash + char;
88
- hash = hash & hash;
89
- }
90
- const colorIndex = Math.abs(hash) % COLOR_PALETTE.length;
91
- const color = {
92
- css: COLOR_PALETTE[colorIndex],
93
- ansi: ANSI_COLORS[colorIndex % ANSI_COLORS.length]
94
- };
95
- namespaceColors.set(namespace, color);
96
- return color;
97
- }
98
- function createDebugLogger(namespace) {
99
- const colors = getColorForNamespace(namespace);
100
- return (...args) => {
101
- const envEnabled = isEnabled(namespace);
102
- const progEnabled = enabledNamespaces.has(namespace) && !disabledNamespaces.has(namespace);
103
- if (envEnabled || progEnabled) if (isNode) {
104
- const coloredNamespace = `${ANSI_BOLD}${colors.ansi}${namespace}${ANSI_RESET}`;
105
- console.log(coloredNamespace, ...args);
106
- } else {
107
- const style1 = `color: ${colors.css}; font-weight: bold`;
108
- console.log(`%c${namespace}%c`, style1, "color: inherit; font-weight: normal", ...args);
109
- }
110
- };
111
- }
112
- const getLogger = (scope) => {
113
- return createDebugLogger(`${ROOT_NAMESPACE}:${scope}`);
114
- };
115
-
116
- //#endregion
117
- //#region src/errors.ts
118
- var EntityMutationError = class extends Error {
119
- constructor(message) {
120
- super(message);
121
- this.name = "EntityMutationError";
122
- }
123
- };
124
- var InvalidExpirationError = class extends Error {
125
- constructor(expiresIn) {
126
- super(`Invalid expiresIn: ${String(expiresIn)}. expiresIn must be a positive integer and a multiple of the Arkiv block time (${require_consts.BLOCK_TIME} seconds), because expiration is measured in whole blocks (1 block = ${require_consts.BLOCK_TIME} seconds).`);
127
- this.name = "InvalidExpirationError";
128
- }
129
- };
130
- var InvalidAttributeError = class extends Error {
131
- constructor(key, value) {
132
- super(`Invalid numeric value for attribute "${key}": ${String(value)}. Numeric attribute values must be integers. To keep numeric ordering/range queries, scale it to an integer (e.g. Math.round(${String(value)} * 1000), dividing by 1000 on read); otherwise store it as a string (e.g. "${String(value)}").`);
133
- this.name = "InvalidAttributeError";
134
- }
135
- };
136
- var NoMoreResultsError = class extends Error {
137
- constructor() {
138
- super("No more results");
139
- this.name = "NoMoreResultsError";
140
- }
141
- };
142
- var NoCursorOrLimitError = class extends Error {
143
- constructor() {
144
- super("Cursor and limit must be defined to fetch next");
145
- this.name = "NoCursorOrLimitError";
146
- }
147
- };
148
- var NoEntityFoundError = class extends Error {
149
- constructor() {
150
- super("No entity found");
151
- this.name = "NoEntityFoundError";
152
- }
153
- };
154
-
155
- //#endregion
156
- //#region src/types/entity.ts
157
- var Entity = class {
158
- key;
159
- contentType;
160
- owner;
161
- creator;
162
- expiresAtBlock;
163
- createdAtBlock;
164
- lastModifiedAtBlock;
165
- transactionIndexInBlock;
166
- operationIndexInTransaction;
167
- payload;
168
- attributes;
169
- constructor(key, contentType = void 0, owner = void 0, creator = void 0, expiresAtBlock = void 0, createdAtBlock = void 0, lastModifiedAtBlock = void 0, transactionIndexInBlock = void 0, operationIndexInTransaction = void 0, payload = void 0, attributes) {
170
- this.key = key;
171
- this.owner = owner;
172
- this.creator = creator;
173
- this.expiresAtBlock = expiresAtBlock;
174
- this.createdAtBlock = createdAtBlock;
175
- this.lastModifiedAtBlock = lastModifiedAtBlock;
176
- this.transactionIndexInBlock = transactionIndexInBlock;
177
- this.operationIndexInTransaction = operationIndexInTransaction;
178
- this.payload = payload;
179
- this.attributes = attributes;
180
- this.contentType = contentType;
181
- }
182
- /**
183
- * Converts the entity payload from bytes to a string and returns it.
184
- * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.
185
- * Throws an error if the conversion from bytes to string fails.
186
- * @returns The entity payload as a string.
187
- */
188
- toText() {
189
- if (this.payload === void 0) throw new Error("Entity has no payload – it was probably queried without withPayload(true) via QueryBuilder");
190
- try {
191
- return (0, viem.bytesToString)(this.payload);
192
- } catch (e) {
193
- throw new Error(`Failed to convert entity payload to text: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
194
- }
195
- }
196
- /**
197
- * Parses the entity payload as JSON and returns the resulting object.
198
- * Throws an error if the payload is undefined, which may occur if the entity was not queried with the withPayload option.
199
- * Throws an error if the payload is empty or cannot be parsed as JSON.
200
- * @returns The parsed JSON object from the entity payload.
201
- */
202
- toJson() {
203
- const text = this.toText();
204
- if (!text) throw new Error("Entity has empty payload, cannot parse as JSON");
205
- try {
206
- return JSON.parse(text);
207
- } catch (e) {
208
- throw new Error(`Failed to parse entity payload as JSON: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
209
- }
210
- }
211
- };
212
-
213
- //#endregion
214
- //#region src/utils/entities.ts
215
- const logger$2 = getLogger("utils:entities");
216
- async function entityFromRpcResult(rpcEntity) {
217
- logger$2("entityFromRpcResult %o", rpcEntity);
218
- return new Entity(rpcEntity.key, rpcEntity.contentType, rpcEntity.owner, rpcEntity.creator, rpcEntity.expiresAt !== void 0 ? BigInt(rpcEntity.expiresAt) : void 0, rpcEntity.createdAtBlock !== void 0 ? BigInt(rpcEntity.createdAtBlock) : void 0, rpcEntity.lastModifiedAtBlock !== void 0 ? BigInt(rpcEntity.lastModifiedAtBlock) : void 0, rpcEntity.transactionIndexInBlock !== void 0 ? BigInt(rpcEntity.transactionIndexInBlock) : void 0, rpcEntity.operationIndexInTransaction !== void 0 ? BigInt(rpcEntity.operationIndexInTransaction) : void 0, rpcEntity.value !== void 0 ? (0, viem.toBytes)(rpcEntity.value) : void 0, [...(rpcEntity.stringAttributes ?? []).map(({ key, value }) => ({
219
- key,
220
- value
221
- })), ...(rpcEntity.numericAttributes ?? []).map(({ key, value }) => ({
222
- key,
223
- value: Number(value)
224
- }))]);
225
- }
226
-
227
- //#endregion
228
- //#region src/query/engine.ts
229
- const logger$1 = getLogger("query:engine");
230
- function processPredicates(predicates) {
231
- const processValue = (value) => {
232
- if (typeof value === "string") return `"${value}"`;
233
- return value;
234
- };
235
- return predicates.map((predicate) => {
236
- switch (predicate.type) {
237
- case "eq": return `${predicate.key} = ${processValue(predicate.value)}`;
238
- case "neq": return `${predicate.key} != ${processValue(predicate.value)}`;
239
- case "gt": return `${predicate.key} > ${processValue(predicate.value)}`;
240
- case "gte": return `${predicate.key} >= ${processValue(predicate.value)}`;
241
- case "lt": return `${predicate.key} < ${processValue(predicate.value)}`;
242
- case "lte": return `${predicate.key} <= ${processValue(predicate.value)}`;
243
- case "not": return `!${predicate.key}`;
244
- case "or": return `(${predicate.predicates.map((predicate$1) => processPredicates([predicate$1])).join(" || ")})`;
245
- case "and": return `(${predicate.predicates.map((predicate$1) => processPredicates([predicate$1])).join(" && ")})`;
246
- default: return "";
247
- }
248
- }).join(" && ");
249
- }
250
- async function processQuery(client, queryParams) {
251
- const { predicates, limit, cursor, ownedBy, createdBy, orderBy, validAtBlock, withAttributes, withMetadata, withPayload, includeData } = queryParams;
252
- logger$1("Processing query with params %o", {
253
- predicates,
254
- cursor,
255
- limit,
256
- ownedBy,
257
- createdBy,
258
- orderBy,
259
- validAtBlock,
260
- withAttributes,
261
- withMetadata,
262
- withPayload,
263
- includeData
264
- });
265
- let query = processPredicates(predicates);
266
- if (ownedBy) query += ` && $owner=${ownedBy}`;
267
- if (createdBy) query += ` && $creator=${createdBy}`;
268
- query = query.trim();
269
- if (query.startsWith("&& ")) query = query.slice(3);
270
- const queryOptions = { includeData: includeData ?? {
271
- key: true,
272
- attributes: withAttributes ?? false,
273
- payload: withPayload ?? false,
274
- contentType: withMetadata ?? false,
275
- expiration: withMetadata ?? false,
276
- owner: withMetadata ?? false,
277
- creator: withMetadata ?? false,
278
- createdAtBlock: withMetadata ?? false,
279
- lastModifiedAtBlock: withMetadata ?? false,
280
- transactionIndexInBlock: withMetadata ?? false,
281
- operationIndexInTransaction: withMetadata ?? false
282
- } };
283
- if (validAtBlock !== void 0) queryOptions.atBlock = (0, viem.numberToHex)(validAtBlock);
284
- if (limit !== void 0) queryOptions.resultsPerPage = (0, viem.numberToHex)(limit);
285
- if (cursor !== void 0) queryOptions.cursor = cursor;
286
- if (orderBy !== void 0) queryOptions.orderBy = orderBy;
287
- logger$1("Built query to send %s %o", query, {
288
- includeData: queryOptions.includeData,
289
- atBlock: queryOptions.atBlock ? (0, viem.hexToNumber)(queryOptions.atBlock) : void 0,
290
- orderBy: queryOptions.orderBy,
291
- resultsPerPage: queryOptions.resultsPerPage,
292
- cursor: queryOptions.cursor
293
- });
294
- const result = await client.request({
295
- method: "arkiv_query",
296
- params: [query, queryOptions]
297
- });
298
- logger$1("Raw result from query %o", result);
299
- return result;
300
- }
301
-
302
- //#endregion
303
- //#region src/query/queryResult.ts
304
- const logger = getLogger("query:result");
305
- /**
306
- * The result of a query. Holds the fetched entities and supports cursor-based pagination.
307
- *
308
- * @typeParam TEntity - The shape of each entity, inferred from the query builder
309
- * (a full {@link Entity}, or a projected object inferred from a `select()` selection).
310
- */
311
- var QueryResult = class {
312
- entities;
313
- _endOfIteration;
314
- _cursor;
315
- _limit;
316
- _validAtBlock;
317
- _queryBuilder;
318
- get queryBuilder() {
319
- return this._queryBuilder;
320
- }
321
- get cursor() {
322
- return this._cursor;
323
- }
324
- constructor(entities, queryBuilder, cursor, limit, validAtBlock) {
325
- this.entities = entities;
326
- this._queryBuilder = queryBuilder;
327
- this._endOfIteration = !limit || entities.length < limit;
328
- this._cursor = cursor;
329
- this._limit = limit;
330
- this._validAtBlock = validAtBlock;
331
- }
332
- async next() {
333
- if (this._cursor === void 0 || this._limit === void 0) throw new NoCursorOrLimitError();
334
- if (this._endOfIteration) throw new NoMoreResultsError();
335
- this._queryBuilder.cursor(this._cursor);
336
- const result = await this._queryBuilder.fetch();
337
- this.entities = result.entities;
338
- this._queryBuilder = result.queryBuilder;
339
- this._endOfIteration = !result.cursor || result.entities.length < this._limit;
340
- this._cursor = result.cursor;
341
- logger("Current block height for next page %s", this._validAtBlock?.toString() ?? "unknown");
342
- }
343
- hasNextPage() {
344
- return !this._endOfIteration;
345
- }
346
- };
347
-
348
- //#endregion
349
- //#region src/query/selection.ts
350
- /**
351
- * Converts a {@link SelectArg} into the {@link RpcIncludeData} understood by the query engine.
352
- * Every field is opt-in — anything not explicitly selected defaults to `false`, including the key.
353
- * `undefined` or `"*"` selects everything.
354
- *
355
- * @param selection - The selection to convert
356
- * @returns The fully-resolved include-data object for the RPC query
357
- * @throws If an empty selection object is provided
358
- *
359
- * @example
360
- * selectionToIncludeData() // everything
361
- * selectionToIncludeData("*") // everything
362
- * selectionToIncludeData({ key: true }) // only the key
363
- * selectionToIncludeData({ owner: true }) // only the owner
364
- */
365
- function selectionToIncludeData(selection) {
366
- if (selection === void 0 || selection === "*") return {
367
- key: true,
368
- attributes: true,
369
- payload: true,
370
- contentType: true,
371
- expiration: true,
372
- owner: true,
373
- creator: true,
374
- createdAtBlock: true,
375
- lastModifiedAtBlock: true,
376
- transactionIndexInBlock: true,
377
- operationIndexInTransaction: true
378
- };
379
- if (!Object.values(selection).some((selected) => selected === true)) throw new Error("select() requires at least one field to be selected. Pass select() or select(\"*\") to select everything.");
380
- return {
381
- key: selection.key ?? false,
382
- attributes: selection.attributes ?? false,
383
- payload: selection.payload ?? false,
384
- contentType: selection.contentType ?? false,
385
- expiration: selection.expiresAtBlock ?? false,
386
- owner: selection.owner ?? false,
387
- creator: selection.creator ?? false,
388
- createdAtBlock: selection.createdAtBlock ?? false,
389
- lastModifiedAtBlock: selection.lastModifiedAtBlock ?? false,
390
- transactionIndexInBlock: selection.transactionIndexInBlock ?? false,
391
- operationIndexInTransaction: selection.operationIndexInTransaction ?? false
392
- };
393
- }
394
-
395
- //#endregion
396
- //#region src/query/queryBuilder.ts
397
- /**
398
- * Helper function to create an ascending order by attribute
399
- * @param attributeName - The name of the attribute to order by
400
- * @param attributeType - The type of the attribute to order by (string or number)
401
- * @returns Input for orderBy method
402
- *
403
- * @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
404
- * helper) have no effect on the returned order. Sort the fetched entities in JavaScript
405
- * instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
406
- *
407
- * @example
408
- * const ascAttribute = asc("name", "string")
409
- */
410
- function asc(attributeName, attributeType) {
411
- return {
412
- name: attributeName,
413
- type: attributeType,
414
- order: "asc"
415
- };
416
- }
417
- /**
418
- * Helper function to create a descending order by attribute
419
- * @param attributeName - The name of the attribute to order by
420
- * @param attributeType - The type of the attribute to order by (string or number)
421
- * @returns Input for orderBy method
422
- *
423
- * @deprecated Server-side ordering is not supported by the network, so `orderBy` (and this
424
- * helper) have no effect on the returned order. Sort the fetched entities in JavaScript
425
- * instead (e.g. `entities.sort(...)`). This function will be removed in a future release.
426
- *
427
- * @example
428
- * const descAttribute = desc("name", "string")
429
- */
430
- function desc(attributeName, attributeType) {
431
- return {
432
- name: attributeName,
433
- type: attributeType,
434
- order: "desc"
435
- };
436
- }
437
- /**
438
- * BaseQueryBuilder holds the query-building logic shared by every query builder
439
- * (filtering, ordering, pagination, execution). It follows the Builder pattern,
440
- * allowing methods to be chained. Subclasses decide how data selection is expressed
441
- * by implementing the protected `selectionParams` method.
442
- *
443
- * Use {@link SelectQueryBuilder} via `client.select()` to build and execute queries.
444
- *
445
- * @typeParam TEntity - The shape of each entity produced by {@link BaseQueryBuilder.fetch}.
446
- */
447
- var BaseQueryBuilder = class {
448
- _client;
449
- _ownedBy;
450
- _createdBy;
451
- _orderBy;
452
- _validAtBlock;
453
- _limit;
454
- _cursor;
455
- _predicates;
456
- constructor(client) {
457
- this._client = client;
458
- this._predicates = [];
459
- }
460
- /**
461
- * Sets the ownedBy filter
462
- * @param ownedBy - The address of the owner
463
- * @returns The query builder instance
464
- *
465
- * @example
466
- * const builder = client.select()
467
- * builder.ownedBy("0x1234567890123456789012345678901234567890")
468
- */
469
- ownedBy(ownedBy) {
470
- this._ownedBy = ownedBy;
471
- return this;
472
- }
473
- /**
474
- * Sets the createdBy filter
475
- * @param createdBy - The address of the creator
476
- * @returns The query builder instance
477
- *
478
- * @example
479
- * const builder = client.select()
480
- * builder.createdBy("0x1234567890123456789012345678901234567890")
481
- */
482
- createdBy(createdBy) {
483
- this._createdBy = createdBy;
484
- return this;
485
- }
486
- orderBy(attributeNameOrOrderByAttribute, attributeType, order = "asc") {
487
- if (!this._orderBy) this._orderBy = [];
488
- const pushOrderByAttribute = ({ name, type, order: order$1 }) => {
489
- this._orderBy?.push({
490
- name,
491
- type: type === "number" ? "numeric" : type,
492
- desc: order$1 === "desc"
493
- });
494
- };
495
- if (typeof attributeNameOrOrderByAttribute === "string") {
496
- if (!attributeType) throw new Error("attributeType is required when using positional orderBy arguments");
497
- pushOrderByAttribute({
498
- name: attributeNameOrOrderByAttribute,
499
- type: attributeType,
500
- order
501
- });
502
- } else pushOrderByAttribute(attributeNameOrOrderByAttribute);
503
- return this;
504
- }
505
- /**
506
- * Sets the limit for the query
507
- * @param limit - The number of entities to return
508
- * @returns The query builder instance
509
- *
510
- * @example
511
- * const builder = client.select()
512
- * builder.limit(10)
513
- */
514
- limit(limit) {
515
- this._limit = limit;
516
- return this;
517
- }
518
- /**
519
- * Sets the cursor for the query - it is advances setting which rather shouldn't be used manually but it is provided from query result if limit is used (pagination).
520
- * @param cursor - The cursor to set which tells to RPC Query server where to start or continue the query.
521
- * @returns The query builder instance
522
- *
523
- * @example
524
- * const builder = client.select()
525
- * builder.cursor("0xABC123")
526
- */
527
- cursor(cursor) {
528
- this._cursor = cursor;
529
- return this;
530
- }
531
- /**
532
- * Sets the validAtBlock for the query which tells at which block height the state we are intested.
533
- * If not set, the latest block is used.
534
- * @param validAtBlock - The block number to set
535
- * @returns The query builder instance
536
- *
537
- * @example
538
- * const builder = client.select()
539
- * builder.validAtBlock(10000)
540
- */
541
- validAtBlock(validAtBlock) {
542
- this._validAtBlock = validAtBlock;
543
- return this;
544
- }
545
- where(...predicates) {
546
- this._predicates.push(...predicates.flat());
547
- return this;
548
- }
549
- /**
550
- * Fetches the entities from the query.
551
- * It will return a QueryResult instance which can be used to fetch the next and previous pages.
552
- * @returns The QueryResult instance {@link QueryResult}
553
- *
554
- * @example
555
- * const builder = client.select()
556
- * const result = await builder.where(eq("name", "John")).fetch()
557
- * // result = { entities: [Entity, Entity, Entity], next: async () => QueryResult, previous: async () => QueryResult }
558
- */
559
- async fetch() {
560
- const queryResult = await processQuery(this._client, {
561
- predicates: this._predicates,
562
- limit: this._limit,
563
- cursor: this._cursor,
564
- ownedBy: this._ownedBy,
565
- createdBy: this._createdBy,
566
- orderBy: this._orderBy,
567
- validAtBlock: this._validAtBlock,
568
- ...this.selectionParams()
569
- });
570
- const entities = await Promise.all(queryResult.data.map((entity) => this.projectEntity(entity)));
571
- this.cursor(queryResult.cursor);
572
- this.validAtBlock(BigInt(queryResult.blockNumber ?? 0));
573
- return new QueryResult(entities, this, this._cursor, this._limit, this._validAtBlock);
574
- }
575
- /**
576
- * Counts the entities from the query.
577
- * @returns The number of entities
578
- *
579
- * @example
580
- * const builder = client.select()
581
- * const result = await builder.where(eq("name", "John")).count()
582
- * // result = 10
583
- */
584
- async count() {
585
- return (await processQuery(this._client, {
586
- predicates: this._predicates,
587
- limit: this._limit,
588
- cursor: this._cursor,
589
- ownedBy: this._ownedBy,
590
- createdBy: this._createdBy,
591
- orderBy: void 0,
592
- validAtBlock: this._validAtBlock,
593
- withAttributes: false,
594
- withMetadata: false,
595
- withPayload: false
596
- })).data.length ?? 0;
597
- }
598
- };
599
- /**
600
- * QueryBuilder is a helper class to build queries to the Arkiv DBChains.
601
- * It can be used to fetch entities from the Arkiv DBChains. It follows the Builder pattern allowing chaining of methods.
602
- *
603
- * By default the result includes only the entity `key`. Additional data is opt-in through
604
- * `withAttributes()`, `withMetadata()` and `withPayload()`.
605
- *
606
- * @deprecated Use {@link SelectQueryBuilder} via `client.select()` instead. Declaring the
607
- * selection up front avoids the common mistake of forgetting to opt in to data and getting back
608
- * entities with only their `key` populated. This class remains for backwards compatibility and
609
- * will be removed in a future release.
610
- *
611
- * @param client - The Arkiv client
612
- * @returns The QueryBuilder instance {@link QueryBuilder}
613
- */
614
- var QueryBuilder = class extends BaseQueryBuilder {
615
- _withAttributes;
616
- _withMetadata;
617
- _withPayload;
618
- /**
619
- * Sets the withAttributes flag which will return the attributes for the entities if true
620
- * @param withAttributes - The boolean value to set
621
- * @returns The QueryBuilder instance
622
- *
623
- * @example
624
- * const builder = client.buildQuery()
625
- * builder.withAttributes(true)
626
- */
627
- withAttributes(withAttributes = true) {
628
- this._withAttributes = withAttributes;
629
- return this;
630
- }
631
- /**
632
- * Sets the withMetadata flag which will return the metadata (like owner, expiredAt, etc.) for the entities if true
633
- * @param withMetadata - The boolean value to set
634
- * @returns The QueryBuilder instance
635
- *
636
- * @example
637
- * const builder = client.buildQuery()
638
- * builder.withMetadata(true)
639
- */
640
- withMetadata(withMetadata = true) {
641
- this._withMetadata = withMetadata;
642
- return this;
643
- }
644
- /**
645
- * Sets the withPayload flag which will return the payload for the entities if true
646
- * @param withPayload - The boolean value to set
647
- * @returns The QueryBuilder instance
648
- *
649
- * @example
650
- * const builder = client.buildQuery()
651
- * builder.withPayload(true)
652
- */
653
- withPayload(withPayload = true) {
654
- this._withPayload = withPayload;
655
- return this;
656
- }
657
- selectionParams() {
658
- return {
659
- withAttributes: this._withAttributes,
660
- withMetadata: this._withMetadata,
661
- withPayload: this._withPayload
662
- };
663
- }
664
- projectEntity(rpcEntity) {
665
- return entityFromRpcResult(rpcEntity);
666
- }
667
- };
668
- /**
669
- * SelectQueryBuilder is the recommended query builder. It requires the selection to be declared
670
- * up front, so results always contain exactly the data you asked for — and the type of each
671
- * returned entity is narrowed to exactly the selected fields.
672
- *
673
- * The selection is fixed at construction time and is flat — each field maps to an entity field.
674
- * Create one via `client.select(...)` rather than constructing it directly, so the result type is
675
- * inferred from the selection.
676
- *
677
- * @typeParam TEntity - The projected entity shape, inferred from the selection by `client.select()`.
678
- *
679
- * @example
680
- * // everything
681
- * await client.select().where(eq("name", "John")).fetch()
682
- * await client.select("*").where(eq("name", "John")).fetch()
683
- * // specific fields
684
- * await client.select({ owner: true, attributes: true }).fetch()
685
- * // a single field — result is typed (flat) { owner: Hex }
686
- * await client.select({ owner: true }).fetch()
687
- */
688
- var SelectQueryBuilder = class extends BaseQueryBuilder {
689
- _includeData;
690
- constructor(client, selection) {
691
- super(client);
692
- this._includeData = selectionToIncludeData(selection);
693
- }
694
- selectionParams() {
695
- return { includeData: this._includeData };
696
- }
697
- async projectEntity(rpcEntity) {
698
- return await entityFromRpcResult(rpcEntity);
699
- }
700
- };
701
-
702
- //#endregion
703
- Object.defineProperty(exports, 'BaseQueryBuilder', {
704
- enumerable: true,
705
- get: function () {
706
- return BaseQueryBuilder;
707
- }
708
- });
709
- Object.defineProperty(exports, 'EntityMutationError', {
710
- enumerable: true,
711
- get: function () {
712
- return EntityMutationError;
713
- }
714
- });
715
- Object.defineProperty(exports, 'InvalidAttributeError', {
716
- enumerable: true,
717
- get: function () {
718
- return InvalidAttributeError;
719
- }
720
- });
721
- Object.defineProperty(exports, 'InvalidExpirationError', {
722
- enumerable: true,
723
- get: function () {
724
- return InvalidExpirationError;
725
- }
726
- });
727
- Object.defineProperty(exports, 'NoCursorOrLimitError', {
728
- enumerable: true,
729
- get: function () {
730
- return NoCursorOrLimitError;
731
- }
732
- });
733
- Object.defineProperty(exports, 'NoEntityFoundError', {
734
- enumerable: true,
735
- get: function () {
736
- return NoEntityFoundError;
737
- }
738
- });
739
- Object.defineProperty(exports, 'NoMoreResultsError', {
740
- enumerable: true,
741
- get: function () {
742
- return NoMoreResultsError;
743
- }
744
- });
745
- Object.defineProperty(exports, 'QueryBuilder', {
746
- enumerable: true,
747
- get: function () {
748
- return QueryBuilder;
749
- }
750
- });
751
- Object.defineProperty(exports, 'QueryResult', {
752
- enumerable: true,
753
- get: function () {
754
- return QueryResult;
755
- }
756
- });
757
- Object.defineProperty(exports, 'SelectQueryBuilder', {
758
- enumerable: true,
759
- get: function () {
760
- return SelectQueryBuilder;
761
- }
762
- });
763
- Object.defineProperty(exports, 'asc', {
764
- enumerable: true,
765
- get: function () {
766
- return asc;
767
- }
768
- });
769
- Object.defineProperty(exports, 'desc', {
770
- enumerable: true,
771
- get: function () {
772
- return desc;
773
- }
774
- });
775
- Object.defineProperty(exports, 'entityFromRpcResult', {
776
- enumerable: true,
777
- get: function () {
778
- return entityFromRpcResult;
779
- }
780
- });
781
- Object.defineProperty(exports, 'getLogger', {
782
- enumerable: true,
783
- get: function () {
784
- return getLogger;
785
- }
786
- });
787
- Object.defineProperty(exports, 'selectionToIncludeData', {
788
- enumerable: true,
789
- get: function () {
790
- return selectionToIncludeData;
791
- }
792
- });