@wishknish/knishio-client-ts 0.9.4 → 0.9.6

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/dist/index.js CHANGED
@@ -2172,11 +2172,9 @@ function verifyOTSSignature(otsFragments, molecularHash, signingAddress) {
2172
2172
  const base17Hash = convertToBase17(molecularHash);
2173
2173
  const enumerated = enumerateMolecularHash(base17Hash);
2174
2174
  const normalized = normalizeMolecularHash(enumerated);
2175
- let ots = otsFragments;
2175
+ const ots = otsFragments;
2176
2176
  if (ots.length !== 2048) {
2177
- if (ots.length !== 2048) {
2178
- return false;
2179
- }
2177
+ return false;
2180
2178
  }
2181
2179
  const otsChunks = [];
2182
2180
  for (let i = 0; i < ots.length; i += CRYPTO_CONSTANTS.KEY_FRAGMENT_SIZE) {
@@ -2679,6 +2677,123 @@ var Meta = class {
2679
2677
  });
2680
2678
  }
2681
2679
  };
2680
+
2681
+ // src/libraries/array.ts
2682
+ function deepCloning(o, h) {
2683
+ let i;
2684
+ let r;
2685
+ let x;
2686
+ const t = [Array, Date, Number, String, Boolean];
2687
+ const s = Object.prototype.toString;
2688
+ h = h || [];
2689
+ for (i = 0; i < h.length; i += 2) {
2690
+ if (o === h[i]) {
2691
+ return h[i + 1];
2692
+ }
2693
+ }
2694
+ if (!r && o && typeof o === "object") {
2695
+ r = {};
2696
+ for (i = 0; i < t.length; i++) {
2697
+ if (s.call(o) === s.call(x = new t[i](o))) {
2698
+ r = i ? x : [];
2699
+ }
2700
+ }
2701
+ h.push(o, r);
2702
+ for (i in o) {
2703
+ if (Object.prototype.hasOwnProperty.call(o, i)) {
2704
+ r[i] = deepCloning(o[i], h);
2705
+ }
2706
+ }
2707
+ }
2708
+ return r || o;
2709
+ }
2710
+ function chunkArray(arr, size) {
2711
+ const chunks = [];
2712
+ for (let i = 0; i < arr.length; i += size) {
2713
+ chunks.push(arr.slice(i, i + size));
2714
+ }
2715
+ return chunks;
2716
+ }
2717
+ function diff(...arrays) {
2718
+ return [].concat(...arrays.map((arr, i) => {
2719
+ const others = arrays.slice(0);
2720
+ others.splice(i, 1);
2721
+ const unique = [...new Set([].concat(...others))];
2722
+ return arr.filter((item) => !unique.includes(item));
2723
+ }));
2724
+ }
2725
+ function intersect(...arrays) {
2726
+ if (arrays.length === 0) return [];
2727
+ if (arrays.length === 1) return arrays[0];
2728
+ return arrays.reduce(
2729
+ (first, second) => first.filter((item) => second.includes(item))
2730
+ );
2731
+ }
2732
+
2733
+ // src/core/PolicyMeta.ts
2734
+ var PolicyMeta = class _PolicyMeta {
2735
+ policy;
2736
+ /**
2737
+ * Create new PolicyMeta instance
2738
+ * Matches JavaScript SDK constructor signature exactly
2739
+ */
2740
+ constructor(policy = {}, metaKeys = []) {
2741
+ this.policy = _PolicyMeta.normalizePolicy(policy);
2742
+ this.fillDefault(metaKeys);
2743
+ }
2744
+ /**
2745
+ * Normalize policy object structure
2746
+ * Matches JavaScript SDK normalizePolicy method exactly
2747
+ */
2748
+ static normalizePolicy(policy = {}) {
2749
+ const policyMeta = {};
2750
+ for (const [policyKey, value] of Object.entries(policy)) {
2751
+ if (value !== null && ["read", "write"].includes(policyKey)) {
2752
+ policyMeta[policyKey] = {};
2753
+ for (const [key, content] of Object.entries(value)) {
2754
+ policyMeta[policyKey][key] = content;
2755
+ }
2756
+ }
2757
+ }
2758
+ return policyMeta;
2759
+ }
2760
+ /**
2761
+ * Fill default policy values for metadata keys
2762
+ * Matches JavaScript SDK fillDefault method exactly
2763
+ */
2764
+ fillDefault(metaKeys = []) {
2765
+ const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
2766
+ const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
2767
+ for (const [type, value] of Object.entries({
2768
+ read: readPolicy,
2769
+ write: writePolicy
2770
+ })) {
2771
+ const policyKey = value.map((item) => item.key);
2772
+ if (!this.policy[type]) {
2773
+ this.policy[type] = {};
2774
+ }
2775
+ for (const key of diff(metaKeys, policyKey)) {
2776
+ if (!this.policy[type][key]) {
2777
+ this.policy[type][key] = type === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
2778
+ }
2779
+ }
2780
+ }
2781
+ }
2782
+ /**
2783
+ * Get the policy object
2784
+ * Matches JavaScript SDK get method exactly
2785
+ */
2786
+ get() {
2787
+ return this.policy;
2788
+ }
2789
+ /**
2790
+ * Convert policy to JSON string
2791
+ * Matches JavaScript SDK toJson method exactly
2792
+ */
2793
+ toJson() {
2794
+ return JSON.stringify(this.get());
2795
+ }
2796
+ };
2682
2797
  var AtomMeta = class _AtomMeta {
2683
2798
  meta;
2684
2799
  /**
@@ -2774,8 +2889,9 @@ var AtomMeta = class _AtomMeta {
2774
2889
  * @return This instance for chaining
2775
2890
  */
2776
2891
  addPolicy(policy) {
2892
+ const policyMeta = new PolicyMeta(policy, Object.keys(this.meta));
2777
2893
  this.merge({
2778
- policy: JSON.stringify(policy)
2894
+ policy: policyMeta.toJson()
2779
2895
  });
2780
2896
  return this;
2781
2897
  }
@@ -3408,6 +3524,87 @@ function createMolecularHash(value) {
3408
3524
  }
3409
3525
  return value;
3410
3526
  }
3527
+
3528
+ // src/core/TokenUnit.ts
3529
+ var TokenUnit = class _TokenUnit {
3530
+ id;
3531
+ name;
3532
+ metas;
3533
+ /**
3534
+ * Create new TokenUnit instance
3535
+ * Matches JavaScript SDK constructor signature exactly
3536
+ */
3537
+ constructor(id, name, metas) {
3538
+ this.id = id;
3539
+ this.name = name;
3540
+ this.metas = metas || {};
3541
+ }
3542
+ /**
3543
+ * Create TokenUnit from GraphQL response data
3544
+ * Matches JavaScript SDK createFromGraphQL method exactly
3545
+ */
3546
+ static createFromGraphQL(data) {
3547
+ let metas = data.metas || {};
3548
+ if (Array.isArray(metas) && metas.length) {
3549
+ try {
3550
+ metas = JSON.parse(metas);
3551
+ if (!metas) {
3552
+ metas = {};
3553
+ }
3554
+ } catch (error) {
3555
+ metas = {};
3556
+ }
3557
+ }
3558
+ return new _TokenUnit(
3559
+ data.id,
3560
+ data.name,
3561
+ metas
3562
+ );
3563
+ }
3564
+ /**
3565
+ * Create TokenUnit from database array data
3566
+ * Matches JavaScript SDK createFromDB method exactly
3567
+ */
3568
+ static createFromDB(data) {
3569
+ return new _TokenUnit(
3570
+ data[0],
3571
+ data[1],
3572
+ data.length > 2 ? data[2] : {}
3573
+ );
3574
+ }
3575
+ /**
3576
+ * Get fragment zone from metadata
3577
+ * Matches JavaScript SDK getFragmentZone method exactly
3578
+ */
3579
+ getFragmentZone() {
3580
+ return this.metas.fragmentZone || null;
3581
+ }
3582
+ /**
3583
+ * Get fused token units from metadata
3584
+ * Matches JavaScript SDK getFusedTokenUnits method exactly
3585
+ */
3586
+ getFusedTokenUnits() {
3587
+ return this.metas.fusedTokenUnits || null;
3588
+ }
3589
+ /**
3590
+ * Convert to data array format
3591
+ * Matches JavaScript SDK toData method exactly
3592
+ */
3593
+ toData() {
3594
+ return [this.id, this.name, this.metas];
3595
+ }
3596
+ /**
3597
+ * Convert to GraphQL response format
3598
+ * Matches JavaScript SDK toGraphQLResponse method exactly
3599
+ */
3600
+ toGraphQLResponse() {
3601
+ return {
3602
+ id: this.id,
3603
+ name: this.name,
3604
+ metas: JSON.stringify(this.metas)
3605
+ };
3606
+ }
3607
+ };
3411
3608
  var Wallet = class _Wallet {
3412
3609
  token;
3413
3610
  balance;
@@ -3548,11 +3745,13 @@ var Wallet = class _Wallet {
3548
3745
  return typeof maybeBundleHash === "string" && isBundleHash(maybeBundleHash);
3549
3746
  }
3550
3747
  /**
3551
- * Get formatted token units from raw data
3552
- * Stub implementation for now
3748
+ * Map raw token-unit tuples to TokenUnit instances.
3749
+ * Matches JS SDK Wallet.getTokenUnits (Wallet.js:190-196). The serialised shape reaches hashed
3750
+ * atom meta via AtomMeta.setAtomWallet -> JSON.stringify(getTokenUnitsData()), so returning raw
3751
+ * tuples here would diverge from every other SDK.
3553
3752
  */
3554
3753
  static getTokenUnits(unitsData) {
3555
- return unitsData;
3754
+ return unitsData.map((unitData) => TokenUnit.createFromDB(unitData));
3556
3755
  }
3557
3756
  /**
3558
3757
  * Create a remainder wallet for transactions
@@ -3833,6 +4032,14 @@ var Wallet = class _Wallet {
3833
4032
  };
3834
4033
  var hexStringRegex = /^[0-9a-fA-F]+$/;
3835
4034
  var base17HashRegex = /^[0-9a-g]+$/;
4035
+ var urlString = (message = "Invalid URL") => z.string().refine((value) => {
4036
+ try {
4037
+ new URL(value);
4038
+ return true;
4039
+ } catch {
4040
+ return false;
4041
+ }
4042
+ }, message);
3836
4043
  z.string().regex(hexStringRegex, "Must be a valid hexadecimal string").brand();
3837
4044
  var WalletAddressSchema = z.string().regex(hexStringRegex, "Wallet address must be hexadecimal").length(64, "Wallet address must be exactly 64 characters").brand();
3838
4045
  var BundleHashSchema = z.string().regex(hexStringRegex, "Bundle hash must be hexadecimal").length(64, "Bundle hash must be exactly 64 characters").brand();
@@ -3841,10 +4048,10 @@ z.string().regex(base17HashRegex, "Molecular hash must be base17 format (0-9,a-g
3841
4048
  var TokenSlugSchema = z.string().min(1, "Token slug cannot be empty").max(64, "Token slug cannot exceed 64 characters").transform((val) => val.toUpperCase()).brand();
3842
4049
  var MetaTypeSchema = z.string().min(1, "Meta type cannot be empty").max(256, "Meta type cannot exceed 256 characters").brand();
3843
4050
  var MetaIdSchema = z.string().min(1, "Meta ID cannot be empty").brand();
3844
- var BatchIdSchema = z.string().min(1, "Batch ID cannot be empty").brand();
4051
+ var BatchIdSchema = z.string().regex(/^[0-9a-fA-F]{64}$/, "Batch ID must be 64 hexadecimal characters").brand();
3845
4052
  var CellSlugSchema = z.string().min(1, "Cell slug cannot be empty").max(64, "Cell slug cannot exceed 64 characters").brand();
3846
4053
  var AtomIsotopeSchema = z.enum(["C", "V", "U", "T", "M", "I", "R", "B", "F"], {
3847
- errorMap: () => ({ message: "Invalid atom isotope. Must be one of: C, V, U, T, M, I, R, B, F" })
4054
+ error: "Invalid atom isotope. Must be one of: C, V, U, T, M, I, R, B, F"
3848
4055
  });
3849
4056
  var MetaDataValueSchema = z.union([
3850
4057
  z.string(),
@@ -3857,7 +4064,7 @@ var AtomMetaDataSchema = z.object({
3857
4064
  value: MetaDataValueSchema
3858
4065
  }).strict();
3859
4066
  var MetaDataSchema = z.lazy(
3860
- () => z.record(z.union([
4067
+ () => z.record(z.string(), z.union([
3861
4068
  MetaDataValueSchema,
3862
4069
  MetaDataSchema,
3863
4070
  z.array(MetaDataSchema)
@@ -3896,7 +4103,7 @@ z.object({
3896
4103
  version: z.number().int().min(1).optional()
3897
4104
  }).strict();
3898
4105
  z.object({
3899
- uri: z.union([z.string().url(), z.array(z.string().url())]).optional(),
4106
+ uri: z.union([urlString(), z.array(urlString())]).optional(),
3900
4107
  cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional(),
3901
4108
  client: z.unknown().optional(),
3902
4109
  socket: z.unknown().optional(),
@@ -3913,7 +4120,7 @@ z.object({
3913
4120
  z.object({
3914
4121
  cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional(),
3915
4122
  encrypt: z.boolean().optional(),
3916
- callback: z.function().args(z.unknown()).returns(z.void()).optional()
4123
+ callback: z.custom((value) => typeof value === "function").optional()
3917
4124
  }).strict();
3918
4125
  z.object({
3919
4126
  cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional()
@@ -3922,7 +4129,7 @@ z.object({
3922
4129
  recipient: z.union([WalletAddressSchema, z.string()]),
3923
4130
  amount: z.union([z.number().positive(), z.string().min(1)]),
3924
4131
  token: z.union([TokenSlugSchema, z.string()]).optional(),
3925
- callbackUrl: z.union([z.string().url(), z.null()]).optional(),
4132
+ callbackUrl: z.union([urlString(), z.null()]).optional(),
3926
4133
  metaType: z.union([MetaTypeSchema, z.string(), z.null()]).optional(),
3927
4134
  metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3928
4135
  meta: z.union([MetaDataSchema, z.null()]).optional()
@@ -3963,7 +4170,7 @@ z.object({
3963
4170
  value: z.union([z.string(), z.null()]).optional(),
3964
4171
  latest: z.union([z.boolean(), z.null()]).optional(),
3965
4172
  filter: z.union([z.array(MetaFilterSchema), z.null()]).optional(),
3966
- queryArgs: z.union([z.record(z.unknown()), z.null()]).optional(),
4173
+ queryArgs: z.union([z.record(z.string(), z.unknown()), z.null()]).optional(),
3967
4174
  count: z.union([z.number().int().min(1), z.null()]).optional(),
3968
4175
  countBy: z.union([z.string(), z.null()]).optional(),
3969
4176
  cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional()
@@ -3988,7 +4195,7 @@ z.object({
3988
4195
  }).strict();
3989
4196
  z.object({
3990
4197
  query: z.string().min(1, "GraphQL query cannot be empty"),
3991
- variables: z.record(z.unknown()).optional(),
4198
+ variables: z.record(z.string(), z.unknown()).optional(),
3992
4199
  operationName: z.union([z.string(), z.null()]).optional()
3993
4200
  }).strict();
3994
4201
  var GraphQLErrorSchema = z.object({
@@ -3998,18 +4205,18 @@ var GraphQLErrorSchema = z.object({
3998
4205
  column: z.number().int().min(1)
3999
4206
  })).optional(),
4000
4207
  path: z.array(z.union([z.string(), z.number()])).optional(),
4001
- extensions: z.record(z.unknown()).optional()
4208
+ extensions: z.record(z.string(), z.unknown()).optional()
4002
4209
  }).strict();
4003
4210
  z.object({
4004
4211
  data: z.unknown().optional(),
4005
4212
  errors: z.array(GraphQLErrorSchema).nullable().optional(),
4006
- extensions: z.record(z.unknown()).optional()
4213
+ extensions: z.record(z.string(), z.unknown()).optional()
4007
4214
  }).strict();
4008
4215
  z.object({
4009
4216
  operationName: z.string().optional(),
4010
4217
  query: z.string().optional(),
4011
- variables: z.record(z.unknown()).optional(),
4012
- callback: z.function().args(z.unknown()).returns(z.void()).optional()
4218
+ variables: z.record(z.string(), z.unknown()).optional(),
4219
+ callback: z.custom((value) => typeof value === "function").optional()
4013
4220
  }).strict();
4014
4221
  z.object({
4015
4222
  valid: z.boolean(),
@@ -4019,7 +4226,7 @@ z.object({
4019
4226
  }).strict();
4020
4227
  z.object({
4021
4228
  operation: z.string().optional(),
4022
- parameters: z.record(z.unknown()).optional(),
4229
+ parameters: z.record(z.string(), z.unknown()).optional(),
4023
4230
  timestamp: z.number().int().min(0).optional(),
4024
4231
  stack: z.string().optional()
4025
4232
  }).strict();
@@ -4165,65 +4372,13 @@ var RuleArgumentException = class extends BaseException {
4165
4372
  };
4166
4373
  var RuleArgumentException_default = RuleArgumentException;
4167
4374
 
4168
- // src/libraries/array.ts
4169
- function deepCloning(o, h) {
4170
- let i;
4171
- let r;
4172
- let x;
4173
- const t = [Array, Date, Number, String, Boolean];
4174
- const s = Object.prototype.toString;
4175
- h = h || [];
4176
- for (i = 0; i < h.length; i += 2) {
4177
- if (o === h[i]) {
4178
- return h[i + 1];
4179
- }
4180
- }
4181
- if (!r && o && typeof o === "object") {
4182
- r = {};
4183
- for (i = 0; i < t.length; i++) {
4184
- if (s.call(o) === s.call(x = new t[i](o))) {
4185
- r = i ? x : [];
4186
- }
4187
- }
4188
- h.push(o, r);
4189
- for (i in o) {
4190
- if (Object.prototype.hasOwnProperty.call(o, i)) {
4191
- r[i] = deepCloning(o[i], h);
4192
- }
4193
- }
4194
- }
4195
- return r || o;
4196
- }
4197
- function chunkArray(arr, size) {
4198
- const chunks = [];
4199
- for (let i = 0; i < arr.length; i += size) {
4200
- chunks.push(arr.slice(i, i + size));
4201
- }
4202
- return chunks;
4203
- }
4204
- function diff(...arrays) {
4205
- return [].concat(...arrays.map((arr, i) => {
4206
- const others = arrays.slice(0);
4207
- others.splice(i, 1);
4208
- const unique = [...new Set([].concat(...others))];
4209
- return arr.filter((item) => !unique.includes(item));
4210
- }));
4211
- }
4212
- function intersect(...arrays) {
4213
- if (arrays.length === 0) return [];
4214
- if (arrays.length === 1) return arrays[0];
4215
- return arrays.reduce(
4216
- (first, second) => first.filter((item) => second.includes(item))
4217
- );
4218
- }
4219
-
4220
4375
  // src/instance/rules/Callback.ts
4221
4376
  init_exception();
4222
4377
  var CallbackParamsSchema = z.object({
4223
4378
  action: z.string().min(1, "Action cannot be empty"),
4224
4379
  metaType: z.union([z.string(), z.null()]).optional(),
4225
4380
  metaId: z.union([z.string(), z.null()]).optional(),
4226
- meta: z.union([z.instanceof(Meta2), z.record(z.unknown()), z.null()]).optional(),
4381
+ meta: z.union([z.instanceof(Meta2), z.record(z.string(), z.unknown()), z.null()]).optional(),
4227
4382
  address: z.union([z.string(), z.null()]).optional(),
4228
4383
  token: z.union([z.string(), z.null()]).optional(),
4229
4384
  amount: z.union([z.string(), z.null()]).optional(),
@@ -5547,6 +5702,51 @@ var Molecule = class _Molecule {
5547
5702
  }));
5548
5703
  return this;
5549
5704
  }
5705
+ /**
5706
+ * Replenishes non-finite token supplies.
5707
+ * Matches JS SDK Molecule.replenishToken (Molecule.js:521-566) exactly.
5708
+ *
5709
+ * Two orderings here are load-bearing for the molecular hash and must not be reordered:
5710
+ * the remainder balance is computed BEFORE the source balance is overwritten, and the
5711
+ * source V-atom is added BEFORE the remainder V-atom.
5712
+ */
5713
+ replenishToken({
5714
+ amount,
5715
+ units = []
5716
+ }) {
5717
+ if (amount < 0) {
5718
+ throw new NegativeAmountException("Molecule::replenishToken() - Amount to replenish must be positive!");
5719
+ }
5720
+ if (!this.sourceWallet || !this.remainderWallet) {
5721
+ throw new Error("Source and remainder wallets required for token replenishment");
5722
+ }
5723
+ if (units.length) {
5724
+ const formatted = Wallet.getTokenUnits(units);
5725
+ this.remainderWallet.tokenUnits = this.sourceWallet.tokenUnits;
5726
+ for (const unit of formatted) {
5727
+ this.remainderWallet.tokenUnits.push(unit);
5728
+ }
5729
+ this.remainderWallet.balance = String(this.remainderWallet.tokenUnits.length);
5730
+ this.sourceWallet.tokenUnits = formatted;
5731
+ this.sourceWallet.balance = String(this.sourceWallet.tokenUnits.length);
5732
+ } else {
5733
+ this.remainderWallet.balance = String(Number(this.sourceWallet.balance) + amount);
5734
+ this.sourceWallet.balance = String(amount);
5735
+ }
5736
+ this.addAtom(Atom.create({
5737
+ isotope: "V",
5738
+ wallet: this.sourceWallet,
5739
+ value: Number(this.sourceWallet.balance)
5740
+ }));
5741
+ this.addAtom(Atom.create({
5742
+ isotope: "V",
5743
+ wallet: this.remainderWallet,
5744
+ value: Number(this.remainderWallet.balance),
5745
+ metaType: "walletBundle",
5746
+ metaId: this.remainderWallet.bundle
5747
+ }));
5748
+ return this;
5749
+ }
5550
5750
  /**
5551
5751
  * Initialize authorization request
5552
5752
  * Creates U-isotope (authorization) atom for requesting auth token
@@ -6081,16 +6281,27 @@ var GraphQLClient = class {
6081
6281
  return createClient$1({
6082
6282
  url: serverUri,
6083
6283
  exchanges,
6084
- // PQ-transport Phase E: when encryption is on, route fetch through the CipherHash wrapper
6085
- // (encrypt the request body to the validator's ML-KEM pubkey, decrypt the response).
6086
- // Omitted → urql uses the global fetch (plaintext).
6087
- ...this.cipherLink ? { fetch: ((input, init) => this.cipherFetch(input, init)) } : {},
6284
+ // urql 5 had no default and always POSTed; urql 6 defaults to 'within-url-limit', which
6285
+ // URL-encodes short queries and sends NO body. That would silently disable the CipherHash
6286
+ // envelope below — cipherFetch's `typeof init.body === 'string'` guard fails on a GET, so
6287
+ // the query would leave as plaintext URL parameters with no error. Pin POST explicitly.
6288
+ preferGetMethod: false,
6289
+ // Always route through our own fetch. Two reasons: (1) PQ-transport Phase E — when
6290
+ // encryption is on, cipherFetch wraps the request body in the CipherHash envelope and
6291
+ // decrypts the response; (2) the 60s timeout. urql's makeFetchSource unconditionally
6292
+ // overwrites init.signal with its own AbortController, so a signal returned from
6293
+ // fetchOptions() is discarded and never fired. Combining it here is the only place it
6294
+ // survives.
6295
+ fetch: ((input, init) => {
6296
+ const timeoutSignal = AbortSignal.timeout(6e4);
6297
+ const signal = init?.signal && typeof AbortSignal.any === "function" ? AbortSignal.any([init.signal, timeoutSignal]) : init?.signal ?? timeoutSignal;
6298
+ const timedInit = { ...init, signal };
6299
+ return this.cipherLink ? this.cipherFetch(input, timedInit) : fetch(input, timedInit);
6300
+ }),
6088
6301
  fetchOptions: () => ({
6089
6302
  headers: {
6090
6303
  "X-Auth-Token": this.$__authToken
6091
- },
6092
- // Add 60 second timeout
6093
- signal: AbortSignal.timeout(6e4)
6304
+ }
6094
6305
  })
6095
6306
  });
6096
6307
  }
@@ -6570,6 +6781,14 @@ var Mutation = class extends Query {
6570
6781
  }
6571
6782
  }
6572
6783
  };
6784
+ var urlString2 = (message = "Invalid URL") => z.string().refine((value) => {
6785
+ try {
6786
+ new URL(value);
6787
+ return true;
6788
+ } catch {
6789
+ return false;
6790
+ }
6791
+ }, message);
6573
6792
  function createBrandedSchema(name, baseSchema = z.string()) {
6574
6793
  return baseSchema.brand(name);
6575
6794
  }
@@ -6595,7 +6814,12 @@ var TokenSlugSchema2 = createBrandedSchema(
6595
6814
  );
6596
6815
  var BatchIdSchema2 = createBrandedSchema(
6597
6816
  "BatchId",
6598
- z.string().uuid("Invalid batch ID format")
6817
+ // 64 hex characters. generateBatchId (src/libraries/crypto.ts) returns either
6818
+ // shake256(molecularHash + index, 256) — 256 bits, 64 hex chars — or randomString(64) over the
6819
+ // alphabet 'abcdef0123456789'. A UUID shape matches nothing this SDK can produce, so the
6820
+ // previous 8-4-4-4-12 regex rejected every real batch ID. Agrees with isBatchId in
6821
+ // src/types/guards.ts.
6822
+ z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid batch ID format")
6599
6823
  );
6600
6824
  var CellSlugSchema2 = createBrandedSchema(
6601
6825
  "CellSlug",
@@ -6639,7 +6863,7 @@ var AtomMetaDataSchema2 = z.object({
6639
6863
  z.object({
6640
6864
  key: z.string(),
6641
6865
  value: z.union([z.string(), z.number(), z.boolean(), z.null()])
6642
- }).passthrough();
6866
+ }).loose();
6643
6867
  var AtomParamsSchema2 = z.object({
6644
6868
  position: z.string().optional(),
6645
6869
  walletAddress: z.union([WalletAddressSchema2, z.string()]).optional(),
@@ -6674,8 +6898,8 @@ var MoleculeParamsSchema2 = z.object({
6674
6898
  }).strict();
6675
6899
  var KnishIOClientConfigSchema2 = z.object({
6676
6900
  uri: z.union([
6677
- z.string().url("Invalid URI format"),
6678
- z.array(z.string().url("Invalid URI format")).min(1)
6901
+ urlString2("Invalid URI format"),
6902
+ z.array(urlString2("Invalid URI format")).min(1)
6679
6903
  ]).optional(),
6680
6904
  cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
6681
6905
  client: z.unknown().optional(),
@@ -6688,11 +6912,11 @@ var KnishIOClientConfigSchema2 = z.object({
6688
6912
  defaultRequestPolicy: z.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional()
6689
6913
  }).strict();
6690
6914
  var EnvironmentConfigSchema = z.object({
6691
- NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
6692
- KNISHIO_NODE_URI: z.string().url().optional(),
6915
+ NODE_ENV: z.enum(["development", "production", "test"]).optional(),
6916
+ KNISHIO_NODE_URI: urlString2().optional(),
6693
6917
  KNISHIO_CELL_SLUG: z.string().optional(),
6694
- KNISHIO_LOGGING: z.string().transform((val) => val === "true").default("false"),
6695
- KNISHIO_SERVER_SDK_VERSION: z.string().transform((val) => parseInt(val, 10)).default("4")
6918
+ KNISHIO_LOGGING: z.string().transform((val) => val === "true").optional(),
6919
+ KNISHIO_SERVER_SDK_VERSION: z.string().transform((val) => parseInt(val, 10)).optional()
6696
6920
  }).partial();
6697
6921
  var TransferParamsSchema2 = z.object({
6698
6922
  recipient: z.union([WalletAddressSchema2, z.string()]),
@@ -6701,7 +6925,7 @@ var TransferParamsSchema2 = z.object({
6701
6925
  "Amount must be positive"
6702
6926
  ),
6703
6927
  token: z.union([TokenSlugSchema2, z.string()]).optional(),
6704
- callbackUrl: z.string().url().optional(),
6928
+ callbackUrl: urlString2().optional(),
6705
6929
  metaType: z.string().optional(),
6706
6930
  metaId: z.string().optional(),
6707
6931
  meta: MetaDataSchema2.optional()
@@ -6742,7 +6966,7 @@ var MetaQueryParamsSchema2 = z.object({
6742
6966
  value: z.string().optional(),
6743
6967
  latest: z.boolean().optional(),
6744
6968
  filter: z.string().optional(),
6745
- queryArgs: z.record(z.unknown()).optional(),
6969
+ queryArgs: z.record(z.string(), z.unknown()).optional(),
6746
6970
  count: z.number().int().min(0).optional(),
6747
6971
  countBy: z.string().optional(),
6748
6972
  cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
@@ -6761,14 +6985,14 @@ var AuthTokenParamsSchema2 = z.object({
6761
6985
  var AuthParamsSchema2 = z.object({
6762
6986
  cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
6763
6987
  encrypt: z.boolean().optional(),
6764
- callback: z.function().optional()
6988
+ callback: z.custom((value) => typeof value === "function").optional()
6765
6989
  }).strict();
6766
6990
  var GuestAuthParamsSchema2 = z.object({
6767
6991
  cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
6768
6992
  }).strict();
6769
6993
  var GraphQLRequestSchema2 = z.object({
6770
6994
  query: z.string().min(1),
6771
- variables: z.record(z.unknown()).optional(),
6995
+ variables: z.record(z.string(), z.unknown()).optional(),
6772
6996
  operationName: z.string().optional()
6773
6997
  }).strict();
6774
6998
  var GraphQLErrorSchema2 = z.object({
@@ -6778,12 +7002,12 @@ var GraphQLErrorSchema2 = z.object({
6778
7002
  column: z.number().int()
6779
7003
  })).optional(),
6780
7004
  path: z.array(z.union([z.string(), z.number()])).optional(),
6781
- extensions: z.record(z.unknown()).optional()
7005
+ extensions: z.record(z.string(), z.unknown()).optional()
6782
7006
  }).strict();
6783
7007
  var GraphQLResponseSchema2 = z.object({
6784
7008
  data: z.unknown().optional(),
6785
7009
  errors: z.array(GraphQLErrorSchema2).optional(),
6786
- extensions: z.record(z.unknown()).optional()
7010
+ extensions: z.record(z.string(), z.unknown()).optional()
6787
7011
  }).strict();
6788
7012
  function safeParse(schema, data) {
6789
7013
  const result = schema.safeParse(data);
@@ -6793,7 +7017,7 @@ function safeParse(schema, data) {
6793
7017
  error: {
6794
7018
  issues: result.error.issues,
6795
7019
  message: result.error.message,
6796
- formatted: result.error.format()
7020
+ formatted: z.treeifyError(result.error)
6797
7021
  }
6798
7022
  };
6799
7023
  }
@@ -7498,89 +7722,6 @@ var ConfigValidator = class _ConfigValidator {
7498
7722
 
7499
7723
  // src/response/ResponseBalance.ts
7500
7724
  init_Response();
7501
-
7502
- // src/core/TokenUnit.ts
7503
- var TokenUnit = class _TokenUnit {
7504
- id;
7505
- name;
7506
- metas;
7507
- /**
7508
- * Create new TokenUnit instance
7509
- * Matches JavaScript SDK constructor signature exactly
7510
- */
7511
- constructor(id, name, metas) {
7512
- this.id = id;
7513
- this.name = name;
7514
- this.metas = metas || {};
7515
- }
7516
- /**
7517
- * Create TokenUnit from GraphQL response data
7518
- * Matches JavaScript SDK createFromGraphQL method exactly
7519
- */
7520
- static createFromGraphQL(data) {
7521
- let metas = data.metas || {};
7522
- if (Array.isArray(metas) && metas.length) {
7523
- try {
7524
- metas = JSON.parse(metas);
7525
- if (!metas) {
7526
- metas = {};
7527
- }
7528
- } catch (error) {
7529
- metas = {};
7530
- }
7531
- }
7532
- return new _TokenUnit(
7533
- data.id,
7534
- data.name,
7535
- metas
7536
- );
7537
- }
7538
- /**
7539
- * Create TokenUnit from database array data
7540
- * Matches JavaScript SDK createFromDB method exactly
7541
- */
7542
- static createFromDB(data) {
7543
- return new _TokenUnit(
7544
- data[0],
7545
- data[1],
7546
- data.length > 2 ? data[2] : {}
7547
- );
7548
- }
7549
- /**
7550
- * Get fragment zone from metadata
7551
- * Matches JavaScript SDK getFragmentZone method exactly
7552
- */
7553
- getFragmentZone() {
7554
- return this.metas.fragmentZone || null;
7555
- }
7556
- /**
7557
- * Get fused token units from metadata
7558
- * Matches JavaScript SDK getFusedTokenUnits method exactly
7559
- */
7560
- getFusedTokenUnits() {
7561
- return this.metas.fusedTokenUnits || null;
7562
- }
7563
- /**
7564
- * Convert to data array format
7565
- * Matches JavaScript SDK toData method exactly
7566
- */
7567
- toData() {
7568
- return [this.id, this.name, this.metas];
7569
- }
7570
- /**
7571
- * Convert to GraphQL response format
7572
- * Matches JavaScript SDK toGraphQLResponse method exactly
7573
- */
7574
- toGraphQLResponse() {
7575
- return {
7576
- id: this.id,
7577
- name: this.name,
7578
- metas: JSON.stringify(this.metas)
7579
- };
7580
- }
7581
- };
7582
-
7583
- // src/response/ResponseBalance.ts
7584
7725
  var ResponseBalance = class _ResponseBalance extends Response2 {
7585
7726
  /**
7586
7727
  * Class constructor
@@ -10089,6 +10230,12 @@ var MutationAppendRequest = class extends MutationProposeMolecule {
10089
10230
  }
10090
10231
  };
10091
10232
 
10233
+ // src/mutation/MutationReplenishToken.ts
10234
+ var MutationReplenishToken = class extends MutationProposeMolecule {
10235
+ fillMolecule() {
10236
+ }
10237
+ };
10238
+
10092
10239
  // src/subscribe/Subscribe.ts
10093
10240
  init_exception();
10094
10241
  var Subscribe = class {
@@ -11522,20 +11669,42 @@ var KnishIOClient = class {
11522
11669
  return response;
11523
11670
  }
11524
11671
  /**
11525
- * Replenish tokens
11672
+ * Replenish a non-finite token supply.
11673
+ * Matches JS SDK KnishIOClient.replenishToken (KnishIOClient.js:2195-2231).
11526
11674
  */
11527
11675
  async replenishToken({
11528
11676
  token,
11529
11677
  amount = null,
11530
11678
  units = null,
11531
- sourceWallet: _sourceWallet = null
11679
+ sourceWallet = null
11532
11680
  }) {
11533
11681
  this.log("info", `KnishIOClient::replenishToken() - Replenishing ${amount || "units"} of ${token}...`);
11534
- return this.requestTokens({
11535
- token,
11536
- amount,
11537
- units
11682
+ if (!sourceWallet) {
11683
+ sourceWallet = (await this.queryBalance({ token }))?.payload();
11684
+ }
11685
+ if (!sourceWallet) {
11686
+ throw new TransferBalanceException("Source wallet is missing or invalid.");
11687
+ }
11688
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
11689
+ const molecule = await this.createMolecule({
11690
+ sourceWallet,
11691
+ remainderWallet
11692
+ });
11693
+ molecule.replenishToken({
11694
+ amount: Number(amount ?? 0),
11695
+ units: units ?? []
11696
+ });
11697
+ molecule.sign({ bundle: this.getBundle() });
11698
+ molecule.check();
11699
+ const mutation = await this.createMoleculeMutation({
11700
+ mutationClass: MutationReplenishToken,
11701
+ molecule
11538
11702
  });
11703
+ const response = await this.executeQuery(mutation);
11704
+ if (!response) {
11705
+ throw new CodeException("Token replenishment failed");
11706
+ }
11707
+ return response;
11539
11708
  }
11540
11709
  /**
11541
11710
  * Fuse token units
@@ -11986,75 +12155,8 @@ var KnishIOClient = class {
11986
12155
 
11987
12156
  // src/index.ts
11988
12157
  init_Response();
11989
-
11990
- // src/core/PolicyMeta.ts
11991
- var PolicyMeta = class _PolicyMeta {
11992
- policy;
11993
- /**
11994
- * Create new PolicyMeta instance
11995
- * Matches JavaScript SDK constructor signature exactly
11996
- */
11997
- constructor(policy = {}, metaKeys = []) {
11998
- this.policy = _PolicyMeta.normalizePolicy(policy);
11999
- this.fillDefault(metaKeys);
12000
- }
12001
- /**
12002
- * Normalize policy object structure
12003
- * Matches JavaScript SDK normalizePolicy method exactly
12004
- */
12005
- static normalizePolicy(policy = {}) {
12006
- const policyMeta = {};
12007
- for (const [policyKey, value] of Object.entries(policy)) {
12008
- if (value !== null && ["read", "write"].includes(policyKey)) {
12009
- policyMeta[policyKey] = {};
12010
- for (const [key, content] of Object.entries(value)) {
12011
- policyMeta[policyKey][key] = content;
12012
- }
12013
- }
12014
- }
12015
- return policyMeta;
12016
- }
12017
- /**
12018
- * Fill default policy values for metadata keys
12019
- * Matches JavaScript SDK fillDefault method exactly
12020
- */
12021
- fillDefault(metaKeys = []) {
12022
- const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
12023
- const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
12024
- for (const [type, value] of Object.entries({
12025
- read: readPolicy,
12026
- write: writePolicy
12027
- })) {
12028
- const policyKey = value.map((item) => item.key);
12029
- if (!this.policy[type]) {
12030
- this.policy[type] = {};
12031
- }
12032
- for (const key of diff(metaKeys, policyKey)) {
12033
- if (!this.policy[type][key]) {
12034
- this.policy[type][key] = type === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
12035
- }
12036
- }
12037
- }
12038
- }
12039
- /**
12040
- * Get the policy object
12041
- * Matches JavaScript SDK get method exactly
12042
- */
12043
- get() {
12044
- return this.policy;
12045
- }
12046
- /**
12047
- * Convert policy to JSON string
12048
- * Matches JavaScript SDK toJson method exactly
12049
- */
12050
- toJson() {
12051
- return JSON.stringify(this.get());
12052
- }
12053
- };
12054
-
12055
- // src/index.ts
12056
12158
  init_exception();
12057
- var SDK_VERSION = "1.0.0";
12159
+ var SDK_VERSION = "0.9.6";
12058
12160
  var SDK_NAME = "KnishIO-Client-TS";
12059
12161
  var COMPATIBLE_SERVER_VERSIONS = [4, 5];
12060
12162
  var SDK_INFO = {