@koralabs/kora-labs-common 6.9.4 → 6.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  /** True when a local RSA key is configured (i.e. signing/verifying needs no AWS). */
4
2
  export declare const isLocalJwtSigner: () => boolean;
5
3
  /** Sign `message` with RS256 — local private key if present, else AWS KMS. */
@@ -1,11 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- /// <reference types="node" />
5
- /// <reference types="node" />
6
- /// <reference types="node" />
7
- /// <reference types="node" />
8
- /// <reference types="node" />
9
1
  import { KMSClient } from '@aws-sdk/client-kms';
10
2
  export type KmsClientLike = Pick<KMSClient, 'send'>;
11
3
  /**
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loadAfterHydratingKmsEnvironment = exports.hydrateKmsEnvironment = exports.decryptKmsCiphertext = exports.isKmsDisabled = void 0;
3
+ exports.isKmsDisabled = void 0;
4
+ exports.decryptKmsCiphertext = decryptKmsCiphertext;
5
+ exports.hydrateKmsEnvironment = hydrateKmsEnvironment;
6
+ exports.loadAfterHydratingKmsEnvironment = loadAfterHydratingKmsEnvironment;
4
7
  const client_kms_1 = require("@aws-sdk/client-kms");
5
8
  const KMS_ENV_BUNDLE_KEY = 'KMS_ENV_BUNDLE_ENC';
6
9
  const KMS_DISABLED_KEY = 'KORA_KMS_DISABLED';
@@ -21,7 +24,6 @@ async function decryptKmsCiphertext(ciphertext, client = new client_kms_1.KMSCli
21
24
  }
22
25
  return Buffer.from(response.Plaintext).toString('utf8');
23
26
  }
24
- exports.decryptKmsCiphertext = decryptKmsCiphertext;
25
27
  async function hydrateKmsEnvironment({ env = process.env, client, keys } = {}) {
26
28
  // Self-host: SOPS/age decrypts the env at deploy time, so the values are already
27
29
  // plaintext and there is no KMS to call. Skip decryption entirely (don't even
@@ -83,9 +85,7 @@ async function hydrateKmsEnvironment({ env = process.env, client, keys } = {}) {
83
85
  }
84
86
  return hydratedKeys;
85
87
  }
86
- exports.hydrateKmsEnvironment = hydrateKmsEnvironment;
87
88
  async function loadAfterHydratingKmsEnvironment(load, options) {
88
89
  await hydrateKmsEnvironment(options);
89
90
  return load();
90
91
  }
91
- exports.loadAfterHydratingKmsEnvironment = loadAfterHydratingKmsEnvironment;
@@ -1,11 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
- /// <reference types="node" />
5
- /// <reference types="node" />
6
- /// <reference types="node" />
7
- /// <reference types="node" />
8
- /// <reference types="node" />
9
1
  export interface ObjectStoreConfig {
10
2
  region: string;
11
3
  endpoint?: string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Process-local short-TTL cache with in-flight de-duplication. Concurrent identical requests share
3
+ * a single upstream fetch, and a successful result is served from memory for `ttlMs`. Failures are
4
+ * NEVER cached (the fetcher promise only writes to the store on resolve). The clock is injectable so
5
+ * TTL behavior is unit-testable. Ported from the handle.me BFF into kora-labs-common.
6
+ */
7
+ export declare class ShortTermCache {
8
+ private readonly now;
9
+ private store;
10
+ private inflight;
11
+ constructor(now?: () => number);
12
+ get<T>(key: string, ttlMs: number, fetcher: () => Promise<T>): Promise<T>;
13
+ delete(key: string): void;
14
+ clear(): void;
15
+ }
16
+ /** Shared process-local cache instance for repetitive chain reads. */
17
+ export declare const sharedShortTermCache: ShortTermCache;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sharedShortTermCache = exports.ShortTermCache = void 0;
4
+ /**
5
+ * Process-local short-TTL cache with in-flight de-duplication. Concurrent identical requests share
6
+ * a single upstream fetch, and a successful result is served from memory for `ttlMs`. Failures are
7
+ * NEVER cached (the fetcher promise only writes to the store on resolve). The clock is injectable so
8
+ * TTL behavior is unit-testable. Ported from the handle.me BFF into kora-labs-common.
9
+ */
10
+ class ShortTermCache {
11
+ constructor(now = Date.now) {
12
+ this.now = now;
13
+ this.store = new Map();
14
+ this.inflight = new Map();
15
+ }
16
+ async get(key, ttlMs, fetcher) {
17
+ const hit = this.store.get(key);
18
+ if (hit && hit.expiresAt > this.now()) {
19
+ return hit.value;
20
+ }
21
+ const pending = this.inflight.get(key);
22
+ if (pending) {
23
+ return pending;
24
+ }
25
+ const promise = (async () => {
26
+ const value = await fetcher();
27
+ this.store.set(key, { value, expiresAt: this.now() + ttlMs });
28
+ return value;
29
+ })().finally(() => {
30
+ this.inflight.delete(key);
31
+ });
32
+ this.inflight.set(key, promise);
33
+ return promise;
34
+ }
35
+ delete(key) {
36
+ this.store.delete(key);
37
+ this.inflight.delete(key);
38
+ }
39
+ clear() {
40
+ this.store.clear();
41
+ this.inflight.clear();
42
+ }
43
+ }
44
+ exports.ShortTermCache = ShortTermCache;
45
+ /** Shared process-local cache instance for repetitive chain reads. */
46
+ exports.sharedShortTermCache = new ShortTermCache();
@@ -0,0 +1,50 @@
1
+ import { AccountAsset, AddressInfo, BackgroundImageDetails, ChainProvider, ChainProviderAsset, ChainProviderUtxo } from './interfaces';
2
+ export interface FailoverOptions {
3
+ /**
4
+ * Cooldown (ms) during which a provider that just failed is skipped as the *start* provider,
5
+ * so a throttled/down provider doesn't add latency to every subsequent call. It is still used
6
+ * as a fallback if the others also fail. Set 0 to disable (pure random start = legacy behavior).
7
+ */
8
+ unhealthyCooldownMs?: number;
9
+ now?: () => number;
10
+ /** Injectable RNG in [0,1) for deterministic start selection in tests. Defaults to Math.random. */
11
+ random?: () => number;
12
+ }
13
+ /**
14
+ * Health-aware failover across interchangeable ChainProviders. Reads start on a healthy provider
15
+ * (random among healthy, else random overall) and fall through to the next on error — giving mutual
16
+ * Koios/Blockfrost redundancy from a single call site. Ported from the handle.me BFF and generalized
17
+ * (no app-level constants) so every repo shares it via kora-labs-common.
18
+ */
19
+ export declare class ChainProviderFailover {
20
+ private providers;
21
+ private unhealthyUntil;
22
+ private readonly cooldownMs;
23
+ private readonly now;
24
+ private readonly random;
25
+ constructor(providers: ChainProvider[], options?: FailoverOptions);
26
+ private isHealthy;
27
+ private getStartIndex;
28
+ private getNextProviderIndex;
29
+ private getResponse;
30
+ getLatestTransactionForAsset(policyId: string, hex: string): Promise<string | null>;
31
+ getLatestBlock(): Promise<{
32
+ height: number;
33
+ slot: number;
34
+ time: number;
35
+ }>;
36
+ getAssets(policyId: string): Promise<{
37
+ policyId: string;
38
+ hex: string;
39
+ }[]>;
40
+ getAssetDatum(policyId: string, hex: string): Promise<string | null>;
41
+ getCip25AssetImage(policyId: string, hex: string): Promise<string | null>;
42
+ getRefScriptCbor(tx: string, policyId: string, hex: string): Promise<string>;
43
+ getTxUtxos(tx: string): Promise<ChainProviderUtxo>;
44
+ getAssetUtxo(policyId: string, hex: string): Promise<ChainProviderAsset | null>;
45
+ getAssetsByStakeKey(stakeKey: string): Promise<AccountAsset[]>;
46
+ getDatumFromHash(datumHash: string): Promise<string | null>;
47
+ getBackgroundImageDetails(policyId: string, hex: string): Promise<BackgroundImageDetails>;
48
+ getAddressInfo(bech32Address: string): Promise<AddressInfo>;
49
+ getAddressUTxOs(bech32Address: string): Promise<ChainProviderAsset[]>;
50
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChainProviderFailover = void 0;
4
+ /**
5
+ * Health-aware failover across interchangeable ChainProviders. Reads start on a healthy provider
6
+ * (random among healthy, else random overall) and fall through to the next on error — giving mutual
7
+ * Koios/Blockfrost redundancy from a single call site. Ported from the handle.me BFF and generalized
8
+ * (no app-level constants) so every repo shares it via kora-labs-common.
9
+ */
10
+ class ChainProviderFailover {
11
+ constructor(providers, options = {}) {
12
+ var _a, _b, _c;
13
+ this.providers = [];
14
+ this.unhealthyUntil = [];
15
+ this.providers = providers;
16
+ this.unhealthyUntil = providers.map(() => 0);
17
+ this.cooldownMs = (_a = options.unhealthyCooldownMs) !== null && _a !== void 0 ? _a : 30000;
18
+ this.now = (_b = options.now) !== null && _b !== void 0 ? _b : Date.now;
19
+ this.random = (_c = options.random) !== null && _c !== void 0 ? _c : Math.random;
20
+ }
21
+ isHealthy(index) {
22
+ return this.unhealthyUntil[index] <= this.now();
23
+ }
24
+ getStartIndex() {
25
+ const healthy = this.providers.map((_, i) => i).filter((i) => this.isHealthy(i));
26
+ const pool = healthy.length > 0 ? healthy : this.providers.map((_, i) => i);
27
+ return pool[Math.floor(this.random() * pool.length)];
28
+ }
29
+ getNextProviderIndex(currentIndex) {
30
+ return (currentIndex + 1) % this.providers.length;
31
+ }
32
+ async getResponse(funcName, args, currentIndex, runNum) {
33
+ const num = runNum !== null && runNum !== void 0 ? runNum : 0;
34
+ const index = currentIndex !== null && currentIndex !== void 0 ? currentIndex : this.getStartIndex();
35
+ const chainProvider = this.providers[index];
36
+ return await chainProvider[funcName](...args).catch((error) => {
37
+ // Mark the failed provider unhealthy for the cooldown window so it isn't chosen as the
38
+ // start provider again immediately; it remains a valid fallback.
39
+ if (this.cooldownMs > 0)
40
+ this.unhealthyUntil[index] = this.now() + this.cooldownMs;
41
+ if (num === this.providers.length - 1)
42
+ throw error;
43
+ return this.getResponse(funcName, args, this.getNextProviderIndex(index), num + 1);
44
+ });
45
+ }
46
+ async getLatestTransactionForAsset(policyId, hex) {
47
+ return this.getResponse('getLatestTransactionForAsset', [policyId, hex]);
48
+ }
49
+ async getLatestBlock() {
50
+ return this.getResponse('getLatestBlock', []);
51
+ }
52
+ async getAssets(policyId) {
53
+ return this.getResponse('getAssets', [policyId]);
54
+ }
55
+ async getAssetDatum(policyId, hex) {
56
+ return this.getResponse('getAssetDatum', [policyId, hex]);
57
+ }
58
+ async getCip25AssetImage(policyId, hex) {
59
+ return this.getResponse('getCip25AssetImage', [policyId, hex]);
60
+ }
61
+ async getRefScriptCbor(tx, policyId, hex) {
62
+ return this.getResponse('getRefScriptCbor', [tx, policyId, hex]);
63
+ }
64
+ async getTxUtxos(tx) {
65
+ return this.getResponse('getTxUtxos', [tx]);
66
+ }
67
+ async getAssetUtxo(policyId, hex) {
68
+ // Asset resolution is correctness-critical (backs handle-resolution chain fallback): a
69
+ // provider lagging a burn returns a stale UTxO and falsely resurrects a de-indexed handle.
70
+ // Prefer Blockfrost (reads the latest asset tx live; Koios's tx index can lag a burn by
71
+ // minutes). Koios stays the failover on error.
72
+ const preferredIndex = this.providers.findIndex((p) => { var _a; return ((_a = p.name) !== null && _a !== void 0 ? _a : '').toLowerCase().includes('blockfrost'); });
73
+ return this.getResponse('getAssetUtxo', [policyId, hex], preferredIndex >= 0 ? preferredIndex : undefined);
74
+ }
75
+ async getAssetsByStakeKey(stakeKey) {
76
+ return this.getResponse('getAssetsByStakeKey', [stakeKey]);
77
+ }
78
+ async getDatumFromHash(datumHash) {
79
+ return this.getResponse('getDatumFromHash', [datumHash]);
80
+ }
81
+ async getBackgroundImageDetails(policyId, hex) {
82
+ return this.getResponse('getBackgroundImageDetails', [policyId, hex]);
83
+ }
84
+ async getAddressInfo(bech32Address) {
85
+ return this.getResponse('getAddressInfo', [bech32Address]);
86
+ }
87
+ async getAddressUTxOs(bech32Address) {
88
+ return this.getResponse('getAddressUTxOs', [bech32Address]);
89
+ }
90
+ }
91
+ exports.ChainProviderFailover = ChainProviderFailover;
@@ -0,0 +1,62 @@
1
+ import { ICreatorDefaults } from '../../handles/interfaces';
2
+ export interface ChainProviderAsset {
3
+ address: string;
4
+ amount: {
5
+ unit: string;
6
+ quantity: string;
7
+ }[];
8
+ inline_datum: string | null;
9
+ output_index: number;
10
+ tx_hash: string;
11
+ data_hash: string | null;
12
+ reference_script_hash?: string | null;
13
+ reference_script_cbor?: string | null;
14
+ }
15
+ export interface ChainProviderUtxo {
16
+ outputs: ChainProviderAsset[];
17
+ }
18
+ export interface AccountAsset {
19
+ asset: string;
20
+ amount: string;
21
+ }
22
+ export interface AddressInfo {
23
+ address: string;
24
+ amount: {
25
+ unit: string;
26
+ quantity: string;
27
+ }[];
28
+ stake_address?: string | null;
29
+ script: boolean;
30
+ }
31
+ export interface BackgroundImageDetails {
32
+ image: string;
33
+ creatorDefaults?: ICreatorDefaults;
34
+ metadata?: Record<string, unknown>;
35
+ }
36
+ /**
37
+ * The unified read contract every chain provider (Koios, Blockfrost, …) implements. The failover
38
+ * orchestrator only depends on this interface, so providers are hot-swappable and mutually redundant.
39
+ */
40
+ export interface ChainProvider {
41
+ name: string;
42
+ getLatestTransactionForAsset(policyId: string, hex: string): Promise<string | null>;
43
+ getLatestBlock(): Promise<{
44
+ height: number;
45
+ slot: number;
46
+ time: number;
47
+ }>;
48
+ getAssets(policyId: string): Promise<{
49
+ policyId: string;
50
+ hex: string;
51
+ }[]>;
52
+ getAssetDatum(policyId: string, hex: string): Promise<string | null>;
53
+ getCip25AssetImage(policyId: string, hex: string): Promise<string | null>;
54
+ getRefScriptCbor(tx: string, policyId: string, hex: string): Promise<string>;
55
+ getTxUtxos(tx: string): Promise<ChainProviderUtxo>;
56
+ getAssetUtxo(policyId: string, hex: string): Promise<ChainProviderAsset | null>;
57
+ getAssetsByStakeKey(stakeKey: string): Promise<AccountAsset[]>;
58
+ getDatumFromHash(datumHash: string): Promise<string | null>;
59
+ getBackgroundImageDetails(policyId: string, hex: string): Promise<BackgroundImageDetails>;
60
+ getAddressInfo(bech32Address: string): Promise<AddressInfo>;
61
+ getAddressUTxOs(bech32Address: string): Promise<ChainProviderAsset[]>;
62
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ export * from './transport/fetchProviderJson';
2
+ export * from './failover/interfaces';
3
+ export * from './failover/ChainProviderFailover';
4
+ export * from './cache/ShortTermCache';
package/chain/index.js ADDED
@@ -0,0 +1,24 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ // Subpath-only module: `@koralabs/kora-labs-common/chain`.
18
+ // NOT re-exported from the root index — this is a server-side chain-access layer and will grow to
19
+ // pull Node-only deps (gRPC/UTxORPC). Keeping it off the root barrel preserves the isomorphic root
20
+ // (same rule the `aws` module follows).
21
+ __exportStar(require("./transport/fetchProviderJson"), exports);
22
+ __exportStar(require("./failover/interfaces"), exports);
23
+ __exportStar(require("./failover/ChainProviderFailover"), exports);
24
+ __exportStar(require("./cache/ShortTermCache"), exports);
@@ -0,0 +1,26 @@
1
+ export type ProviderName = 'Koios' | 'Blockfrost';
2
+ type ProviderFetcher = (url: string, init?: {
3
+ method?: string;
4
+ headers?: Record<string, string>;
5
+ body?: string;
6
+ }) => Promise<{
7
+ ok: boolean;
8
+ status: number;
9
+ statusText: string;
10
+ text: () => Promise<string>;
11
+ }>;
12
+ export interface ProviderRequestOptions {
13
+ provider: ProviderName;
14
+ url: string;
15
+ method?: string;
16
+ headers?: Record<string, string>;
17
+ body?: string;
18
+ maxRetries?: number;
19
+ retryBaseDelayMs?: number;
20
+ maxRps?: number;
21
+ rateLimitKey?: string;
22
+ fetcher?: ProviderFetcher;
23
+ }
24
+ export declare const isRetriableError: (provider: ProviderName, error: any) => boolean;
25
+ export declare const fetchProviderJson: <T>({ provider, url, method, headers, body, maxRetries, retryBaseDelayMs, maxRps, rateLimitKey, fetcher }: ProviderRequestOptions) => Promise<T>;
26
+ export {};
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchProviderJson = exports.isRetriableError = void 0;
4
+ const utils_1 = require("../../utils");
5
+ const DEFAULT_MAX_RPS = 5;
6
+ const DEFAULT_MAX_RETRIES = 2;
7
+ const DEFAULT_RETRY_BASE_DELAY_MS = 500;
8
+ const RETRIABLE_STATUS_CODES = new Set([403, 408, 425, 429, 500, 502, 503, 504]);
9
+ const RETRIABLE_MESSAGE_SNIPPETS = [
10
+ 'terminated',
11
+ 'socket',
12
+ 'econnreset',
13
+ 'fetch failed',
14
+ 'gateway timeout',
15
+ 'too many requests',
16
+ 'payload too large',
17
+ 'timed out acquiring connection from connection pool',
18
+ 'rate limit',
19
+ 'service unavailable',
20
+ 'temporarily unavailable'
21
+ ];
22
+ const rateLimitStates = new Map();
23
+ const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
24
+ const getRateLimitState = (key) => {
25
+ const existing = rateLimitStates.get(key);
26
+ if (existing)
27
+ return existing;
28
+ const state = { pending: [], processing: false, maxRps: DEFAULT_MAX_RPS };
29
+ rateLimitStates.set(key, state);
30
+ return state;
31
+ };
32
+ const processRateLimitedQueue = async (key) => {
33
+ const state = getRateLimitState(key);
34
+ if (state.processing)
35
+ return;
36
+ state.processing = true;
37
+ try {
38
+ while (state.pending.length > 0) {
39
+ const pending = state.pending.splice(0, state.pending.length);
40
+ const delayInMilliseconds = Math.ceil(1000 / Math.max(1, state.maxRps));
41
+ await (0, utils_1.asyncForEach)(pending, async (queuedTask) => {
42
+ try {
43
+ const value = await queuedTask.task();
44
+ queuedTask.resolve(value);
45
+ }
46
+ catch (error) {
47
+ queuedTask.reject(error);
48
+ }
49
+ }, delayInMilliseconds);
50
+ }
51
+ }
52
+ finally {
53
+ state.processing = false;
54
+ if (state.pending.length > 0) {
55
+ void processRateLimitedQueue(key);
56
+ }
57
+ }
58
+ };
59
+ const runRateLimitedTask = (key, maxRps, task) => new Promise((resolve, reject) => {
60
+ const state = getRateLimitState(key);
61
+ state.maxRps = maxRps;
62
+ state.pending.push({ task, resolve, reject });
63
+ void processRateLimitedQueue(key);
64
+ });
65
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
66
+ const parseJson = (text) => {
67
+ if (!text)
68
+ return { value: null, parseError: null };
69
+ try {
70
+ return { value: JSON.parse(text), parseError: null };
71
+ }
72
+ catch (error) {
73
+ return { value: null, parseError: error };
74
+ }
75
+ };
76
+ const getProviderPayloadError = (provider, value) => {
77
+ if (!isRecord(value))
78
+ return null;
79
+ if (provider === 'Koios') {
80
+ if (typeof value.code === 'string' && typeof value.message === 'string') {
81
+ return value;
82
+ }
83
+ return null;
84
+ }
85
+ if (typeof value.error === 'string' && (typeof value.status_code === 'number' || typeof value.message === 'string')) {
86
+ return value;
87
+ }
88
+ return null;
89
+ };
90
+ const createProviderError = ({ provider, status, statusText, payload, responseText, cause }) => {
91
+ const error = new Error(`${provider} request failed: ${status} ${statusText}`.trim());
92
+ if (cause)
93
+ error.cause = cause;
94
+ error.status = status;
95
+ error.statusText = statusText;
96
+ if (payload !== undefined) {
97
+ error[`${provider.toLowerCase()}Response`] = payload;
98
+ }
99
+ if (responseText) {
100
+ error.responseText = responseText.slice(0, 512);
101
+ }
102
+ return error;
103
+ };
104
+ const messageLooksRetriable = (value) => RETRIABLE_MESSAGE_SNIPPETS.some((snippet) => value.includes(snippet));
105
+ const isRetriableError = (provider, error) => {
106
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
107
+ const status = Number((_j = (_g = (_e = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.status) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.statusCode) !== null && _b !== void 0 ? _b : error === null || error === void 0 ? void 0 : error.status_code) !== null && _c !== void 0 ? _c : (_d = error === null || error === void 0 ? void 0 : error.koiosResponse) === null || _d === void 0 ? void 0 : _d.status) !== null && _e !== void 0 ? _e : (_f = error === null || error === void 0 ? void 0 : error.koiosResponse) === null || _f === void 0 ? void 0 : _f.status_code) !== null && _g !== void 0 ? _g : (_h = error === null || error === void 0 ? void 0 : error.blockfrostResponse) === null || _h === void 0 ? void 0 : _h.status) !== null && _j !== void 0 ? _j : (_k = error === null || error === void 0 ? void 0 : error.blockfrostResponse) === null || _k === void 0 ? void 0 : _k.status_code);
108
+ if (RETRIABLE_STATUS_CODES.has(status))
109
+ return true;
110
+ const message = `${(_l = error === null || error === void 0 ? void 0 : error.message) !== null && _l !== void 0 ? _l : ''} ${(_o = (_m = error === null || error === void 0 ? void 0 : error.cause) === null || _m === void 0 ? void 0 : _m.message) !== null && _o !== void 0 ? _o : ''}`.toLowerCase();
111
+ if (messageLooksRetriable(message))
112
+ return true;
113
+ const code = `${(_p = error === null || error === void 0 ? void 0 : error.code) !== null && _p !== void 0 ? _p : ''}`.toLowerCase();
114
+ const causeCode = `${(_r = (_q = error === null || error === void 0 ? void 0 : error.cause) === null || _q === void 0 ? void 0 : _q.code) !== null && _r !== void 0 ? _r : ''}`.toLowerCase();
115
+ if (['und_err_socket', 'econnreset', 'etimedout', 'eai_again'].includes(code))
116
+ return true;
117
+ if (['und_err_socket', 'econnreset', 'etimedout', 'eai_again'].includes(causeCode))
118
+ return true;
119
+ const payload = provider === 'Koios' ? error === null || error === void 0 ? void 0 : error.koiosResponse : error === null || error === void 0 ? void 0 : error.blockfrostResponse;
120
+ const payloadMessage = `${(_t = (_s = payload === null || payload === void 0 ? void 0 : payload.message) !== null && _s !== void 0 ? _s : payload === null || payload === void 0 ? void 0 : payload.error) !== null && _t !== void 0 ? _t : ''}`.toLowerCase();
121
+ if (messageLooksRetriable(payloadMessage))
122
+ return true;
123
+ if (provider === 'Koios' && `${(_u = payload === null || payload === void 0 ? void 0 : payload.code) !== null && _u !== void 0 ? _u : ''}`.toLowerCase() === 'pgrst003')
124
+ return true;
125
+ return false;
126
+ };
127
+ exports.isRetriableError = isRetriableError;
128
+ const defaultFetch = (url, init) => globalThis.fetch(url, init);
129
+ const fetchProviderJson = async ({ provider, url, method = 'GET', headers, body, maxRetries = DEFAULT_MAX_RETRIES, retryBaseDelayMs = DEFAULT_RETRY_BASE_DELAY_MS, maxRps = DEFAULT_MAX_RPS, rateLimitKey = provider, fetcher = defaultFetch }) => {
130
+ var _a, _b, _c, _d;
131
+ let attempt = 0;
132
+ // Retry loop: exits only via return (success) or throw (non-retriable / retries exhausted).
133
+ // eslint-disable-next-line no-constant-condition
134
+ while (true) {
135
+ try {
136
+ const response = await runRateLimitedTask(rateLimitKey, maxRps, () => fetcher(url, { method, headers, body }));
137
+ const responseText = await response.text();
138
+ const { value: parsed, parseError } = parseJson(responseText);
139
+ if (parseError && responseText) {
140
+ throw createProviderError({
141
+ provider,
142
+ status: response.status,
143
+ statusText: response.statusText,
144
+ responseText,
145
+ cause: parseError
146
+ });
147
+ }
148
+ const payloadError = getProviderPayloadError(provider, parsed);
149
+ if (!response.ok || payloadError) {
150
+ const status = Number((_b = (_a = payloadError === null || payloadError === void 0 ? void 0 : payloadError.status_code) !== null && _a !== void 0 ? _a : payloadError === null || payloadError === void 0 ? void 0 : payloadError.status) !== null && _b !== void 0 ? _b : response.status);
151
+ const statusText = response.statusText || `${(_d = (_c = payloadError === null || payloadError === void 0 ? void 0 : payloadError.error) !== null && _c !== void 0 ? _c : payloadError === null || payloadError === void 0 ? void 0 : payloadError.message) !== null && _d !== void 0 ? _d : 'Request failed'}`;
152
+ throw createProviderError({ provider, status, statusText, payload: payloadError !== null && payloadError !== void 0 ? payloadError : parsed, responseText });
153
+ }
154
+ return parsed;
155
+ }
156
+ catch (error) {
157
+ if (attempt >= maxRetries || !(0, exports.isRetriableError)(provider, error)) {
158
+ throw error;
159
+ }
160
+ attempt++;
161
+ await delay(retryBaseDelayMs * attempt);
162
+ }
163
+ }
164
+ };
165
+ exports.fetchProviderJson = fetchProviderJson;
@@ -9,7 +9,7 @@ var ComputeEnvironment;
9
9
  ComputeEnvironment["AWS_EC2"] = "aws_ec2";
10
10
  ComputeEnvironment["AWS_OTHER"] = "aws_other";
11
11
  ComputeEnvironment["OTHER"] = "other";
12
- })(ComputeEnvironment = exports.ComputeEnvironment || (exports.ComputeEnvironment = {}));
12
+ })(ComputeEnvironment || (exports.ComputeEnvironment = ComputeEnvironment = {}));
13
13
  class Environment {
14
14
  static async getComputeEnvironment() {
15
15
  if (process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.AWS_EXECUTION_ENV) {
@@ -73,14 +73,14 @@ class Environment {
73
73
  const response = await fetch('http://169.254.169.254/latest/meta-data/tags/instance/Name');
74
74
  return response.text();
75
75
  }
76
- catch (err) {
76
+ catch (_a) {
77
77
  // swallow
78
78
  }
79
79
  try {
80
80
  const response = await fetch('http://169.254.169.254/latest/meta-data/instance-id');
81
81
  return response.text();
82
82
  }
83
- catch (err) {
83
+ catch (_b) {
84
84
  // swallow
85
85
  }
86
86
  return null;
@@ -90,7 +90,7 @@ class Environment {
90
90
  const response = await fetch('http://169.254.170.2/v2/metadata');
91
91
  return await response.json();
92
92
  }
93
- catch (err) {
93
+ catch (_a) {
94
94
  return null;
95
95
  }
96
96
  }
package/fn/index.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  interface AlbEvent {
4
2
  requestContext: {
5
3
  elb: {
package/fn/index.js CHANGED
@@ -61,7 +61,7 @@ const invokeExpressViaAlb = async (albHandler, ctx, input) => {
61
61
  !/^text\//.test(ctype) &&
62
62
  !/(json|xml|x-www-form-urlencoded|javascript|graphql)/.test(ctype);
63
63
  const event = {
64
- requestContext: { elb: { targetGroupArn: 'arn:kora:fn' } },
64
+ requestContext: { elb: { targetGroupArn: 'arn:kora:fn' } }, // marks this as an ALB event
65
65
  httpMethod: h.method,
66
66
  path: url.pathname,
67
67
  queryStringParameters: Object.keys(qs).length ? qs : null,
package/handles/api.js CHANGED
@@ -23,7 +23,6 @@ class HandlesApi {
23
23
  return handleJson;
24
24
  }
25
25
  static async apiRequest(url, headers, body) {
26
- body;
27
26
  if (!HandlesApi._host) {
28
27
  throw new Error('HandlesApi has not been initialized. Please call HandlesApi.init(<network>)');
29
28
  }
@@ -31,7 +31,7 @@ var ERROR_TEXT;
31
31
  ERROR_TEXT["HANDLE_PAGE_INVALID"] = "'page' must be a number";
32
32
  ERROR_TEXT["HANDLE_SLOT_NUMBER_INVALID"] = "'slot_number' must be a number";
33
33
  ERROR_TEXT["HANDLE_PAGE_AND_SLOT_NUMBER_INVALID"] = "'page' and 'slot_number' can't be used together";
34
- })(ERROR_TEXT = exports.ERROR_TEXT || (exports.ERROR_TEXT = {}));
34
+ })(ERROR_TEXT || (exports.ERROR_TEXT = ERROR_TEXT = {}));
35
35
  exports.HANDLES_PER_PAGE_MAX = 1000;
36
36
  exports.EMPTY = '|empty|';
37
37
  exports.TWELVE_HOURS_IN_SLOTS = 43200; // value comes from the securityParam here: https://cips.cardano.org/cips/cip9/#nonupdatableparameters then converted to slots
@@ -19,4 +19,4 @@ var ScriptType;
19
19
  ScriptType["HAL_REF_SPEND_PROXY"] = "halrefprx";
20
20
  ScriptType["HAL_REF_SPEND"] = "halref";
21
21
  ScriptType["HAL_ROYALTY_SPEND"] = "halroy";
22
- })(ScriptType = exports.ScriptType || (exports.ScriptType = {}));
22
+ })(ScriptType || (exports.ScriptType = ScriptType = {}));
@@ -6,7 +6,7 @@ var UTxOFunctionName;
6
6
  UTxOFunctionName["ADD_UTXO"] = "addUtxo";
7
7
  UTxOFunctionName["UPDATE_HOLDER_INDEX"] = "updateHolderIndex";
8
8
  UTxOFunctionName["UPDATE_HANDLE_INDEXES"] = "updateHandleIndexes";
9
- })(UTxOFunctionName = exports.UTxOFunctionName || (exports.UTxOFunctionName = {}));
9
+ })(UTxOFunctionName || (exports.UTxOFunctionName = UTxOFunctionName = {}));
10
10
  var LockedLambdaReason;
11
11
  (function (LockedLambdaReason) {
12
12
  LockedLambdaReason["REINDEX"] = "REINDEX";
@@ -16,7 +16,7 @@ var LockedLambdaReason;
16
16
  LockedLambdaReason["ROLLBACK_20"] = "ROLLBACK_20";
17
17
  LockedLambdaReason["UTXO_IMPORT"] = "UTXO_IMPORT";
18
18
  LockedLambdaReason["UNLOCKED"] = "";
19
- })(LockedLambdaReason = exports.LockedLambdaReason || (exports.LockedLambdaReason = {}));
19
+ })(LockedLambdaReason || (exports.LockedLambdaReason = LockedLambdaReason = {}));
20
20
  var IndexNames;
21
21
  (function (IndexNames) {
22
22
  IndexNames["ADDRESS"] = "address";
@@ -39,4 +39,4 @@ var IndexNames;
39
39
  IndexNames["SUBHANDLE"] = "subhandle";
40
40
  IndexNames["UTXO"] = "utxo";
41
41
  IndexNames["UTXO_SLOT"] = "utxo_slot";
42
- })(IndexNames = exports.IndexNames || (exports.IndexNames = {}));
42
+ })(IndexNames || (exports.IndexNames = IndexNames = {}));
@@ -2,10 +2,10 @@ import { BoolInt, FeaturedItemType, HexString, HexStringOrEmpty } from '../../ty
2
2
  import type { ScriptDetails } from './ScriptDetails';
3
3
  import { UTxOWithTxInfo } from '../UTxO';
4
4
  export declare enum Rarity {
5
- basic = "basic",
6
- common = "common",
7
- rare = "rare",
8
- ultra_rare = "ultra_rare",
5
+ basic = "basic",// - 8-15 characters
6
+ common = "common",// - 4-7 characters
7
+ rare = "rare",// - 3 characters
8
+ ultra_rare = "ultra_rare",// - 2 characters
9
9
  legendary = "legendary"
10
10
  }
11
11
  export interface SocialItem {
@@ -22,18 +22,18 @@ var Rarity;
22
22
  Rarity["rare"] = "rare";
23
23
  Rarity["ultra_rare"] = "ultra_rare";
24
24
  Rarity["legendary"] = "legendary"; // - 1 character
25
- })(Rarity = exports.Rarity || (exports.Rarity = {}));
25
+ })(Rarity || (exports.Rarity = Rarity = {}));
26
26
  var HandleType;
27
27
  (function (HandleType) {
28
28
  HandleType["VIRTUAL_SUBHANDLE"] = "virtual_subhandle";
29
29
  HandleType["NFT_SUBHANDLE"] = "nft_subhandle";
30
30
  HandleType["HANDLE"] = "handle";
31
- })(HandleType = exports.HandleType || (exports.HandleType = {}));
31
+ })(HandleType || (exports.HandleType = HandleType = {}));
32
32
  var SubHandleType;
33
33
  (function (SubHandleType) {
34
34
  SubHandleType["VIRTUAL"] = "virtual";
35
35
  SubHandleType["NFT"] = "nft";
36
- })(SubHandleType = exports.SubHandleType || (exports.SubHandleType = {}));
36
+ })(SubHandleType || (exports.SubHandleType = SubHandleType = {}));
37
37
  var OAuthSocial;
38
38
  (function (OAuthSocial) {
39
39
  OAuthSocial[OAuthSocial["twitter"] = 0] = "twitter";
@@ -55,7 +55,7 @@ var OAuthSocial;
55
55
  OAuthSocial[OAuthSocial["spotify"] = 16] = "spotify";
56
56
  OAuthSocial[OAuthSocial["soundcloud"] = 17] = "soundcloud";
57
57
  OAuthSocial[OAuthSocial["paypal"] = 18] = "paypal";
58
- })(OAuthSocial = exports.OAuthSocial || (exports.OAuthSocial = {}));
58
+ })(OAuthSocial || (exports.OAuthSocial = OAuthSocial = {}));
59
59
  var AvailabilityResponseCode;
60
60
  (function (AvailabilityResponseCode) {
61
61
  AvailabilityResponseCode[AvailabilityResponseCode["AVAILABLE"] = 200] = "AVAILABLE";
@@ -63,5 +63,5 @@ var AvailabilityResponseCode;
63
63
  AvailabilityResponseCode[AvailabilityResponseCode["NOT_AVAILABLE_FOR_LEGAL_REASONS"] = 451] = "NOT_AVAILABLE_FOR_LEGAL_REASONS";
64
64
  AvailabilityResponseCode[AvailabilityResponseCode["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
65
65
  AvailabilityResponseCode[AvailabilityResponseCode["LOCKED"] = 423] = "LOCKED";
66
- })(AvailabilityResponseCode = exports.AvailabilityResponseCode || (exports.AvailabilityResponseCode = {}));
66
+ })(AvailabilityResponseCode || (exports.AvailabilityResponseCode = AvailabilityResponseCode = {}));
67
67
  __exportStar(require("./WalletHandle"), exports);
@@ -18,7 +18,7 @@ exports.HANDLE_POLICIES = {
18
18
  getActivePolicy(network, isDeMi = false, atSlot) {
19
19
  var _a;
20
20
  const theSlot = atSlot ? atSlot : (0, utils_1.getSlotNumberFromDate)(new Date(Date.now()));
21
- return (_a = Object.entries(this[network]).find(([, value]) => { var _a; return value.firstMintingSlot <= theSlot && ((_a = value.lastMintingSlot) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY) >= theSlot && value.isDeMi == isDeMi; })) === null || _a === void 0 ? void 0 : _a[0];
21
+ return (_a = Object.entries(this[network]).find(([, value]) => { var _a, _b; return value.firstMintingSlot <= theSlot && ((_a = value.lastMintingSlot) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY) >= theSlot && ((_b = value.isDeMi) !== null && _b !== void 0 ? _b : false) == isDeMi; })) === null || _a === void 0 ? void 0 : _a[0];
22
22
  },
23
23
  contains(network, policyId) {
24
24
  return Object.keys(this[network]).includes(policyId);
@@ -7,7 +7,7 @@ export declare const buildMetadata: ({ handleName, handleType, cid, ogNumber }:
7
7
  handleName: string;
8
8
  handleType: HandleType;
9
9
  cid: string;
10
- ogNumber?: number | undefined;
10
+ ogNumber?: number;
11
11
  }) => IHandleMetadata;
12
12
  export declare const checkHandlePattern: (handle: string, root?: string) => {
13
13
  valid: boolean;
package/logger/index.js CHANGED
@@ -26,7 +26,7 @@ var LogCategory;
26
26
  LogCategory["FATAL"] = "FATAL";
27
27
  LogCategory["NOTIFY"] = "NOTIFY";
28
28
  LogCategory["USER_ISSUE"] = "USER_ISSUE";
29
- })(LogCategory = exports.LogCategory || (exports.LogCategory = {}));
29
+ })(LogCategory || (exports.LogCategory = LogCategory = {}));
30
30
  const ANSI_RESET = '\x1b[0m';
31
31
  const ANSI_BLUE = '\x1b[34m';
32
32
  const ANSI_GREEN = '\x1b[32m';
package/mpt/index.js CHANGED
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.computeMintingDataRoot = exports.buildMintingDataTrie = exports.Trie = exports.labelSet = void 0;
27
37
  // Server-only (Node) MPT module. Pulls @aiken-lang/merkle-patricia-forestry (native `level`/`blake2b`)
package/mpt/labelSet.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  /** Does the canonical label set contain `label`? */
4
2
  export declare const contains: (set: string, label: string) => boolean;
5
3
  /** Insert `label`, keeping the set sorted ascending. Throws if already present. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koralabs/kora-labs-common",
3
- "version": "6.9.4",
3
+ "version": "6.10.0",
4
4
  "description": "Kora Labs Common Utilities",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -43,12 +43,12 @@
43
43
  "@types/jest": "^30.0.0",
44
44
  "@types/node": "^22.15.17",
45
45
  "@types/pluralize": "^0.0.29",
46
- "@typescript-eslint/eslint-plugin": "^7.6.0",
47
- "@typescript-eslint/parser": "^7.6.0",
48
- "eslint": "^8.57.0",
46
+ "@typescript-eslint/eslint-plugin": "^8.67.0",
47
+ "@typescript-eslint/parser": "^8.67.0",
48
+ "eslint": "^8.57.1",
49
49
  "jest": "^30.4.2",
50
50
  "ts-jest": "^29.4.11",
51
- "typescript": "^4.7.3"
51
+ "typescript": "^5.9.3"
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-kms": "^3.1003.0",
@@ -63,8 +63,8 @@
63
63
  "pluralize-esm": "^9.0.5"
64
64
  },
65
65
  "overrides": {
66
- "js-yaml": "4.3.0",
67
- "brace-expansion": "5.0.8"
66
+ "js-yaml": "4.3.1",
67
+ "brace-expansion": "5.0.9"
68
68
  },
69
69
  "peerDependencies": {
70
70
  "@aiken-lang/merkle-patricia-forestry": "^1.2.0"
package/types/index.js CHANGED
@@ -32,14 +32,14 @@ var AssetNameLabel;
32
32
  AssetNameLabel["LBL_100"] = "000643b0";
33
33
  AssetNameLabel["LBL_222"] = "000de140";
34
34
  AssetNameLabel["LBL_444"] = "001bc280";
35
- })(AssetNameLabel = exports.AssetNameLabel || (exports.AssetNameLabel = {}));
35
+ })(AssetNameLabel || (exports.AssetNameLabel = AssetNameLabel = {}));
36
36
  var CardanoNetwork;
37
37
  (function (CardanoNetwork) {
38
38
  CardanoNetwork["MAINNET"] = "MAINNET";
39
39
  CardanoNetwork["PREPROD"] = "PREPROD";
40
40
  CardanoNetwork["PREVIEW"] = "PREVIEW";
41
41
  CardanoNetwork["UNSET"] = "UNSET";
42
- })(CardanoNetwork = exports.CardanoNetwork || (exports.CardanoNetwork = {}));
42
+ })(CardanoNetwork || (exports.CardanoNetwork = CardanoNetwork = {}));
43
43
  var AddressType;
44
44
  (function (AddressType) {
45
45
  AddressType["Wallet"] = "wallet";
@@ -48,9 +48,9 @@ var AddressType;
48
48
  AddressType["Reward"] = "reward";
49
49
  AddressType["Other"] = "other";
50
50
  AddressType["Drep"] = "drep";
51
- })(AddressType = exports.AddressType || (exports.AddressType = {}));
51
+ })(AddressType || (exports.AddressType = AddressType = {}));
52
52
  var StakeAddressType;
53
53
  (function (StakeAddressType) {
54
54
  StakeAddressType["Script"] = "f";
55
55
  StakeAddressType["Key"] = "e";
56
- })(StakeAddressType = exports.StakeAddressType || (exports.StakeAddressType = {}));
56
+ })(StakeAddressType || (exports.StakeAddressType = StakeAddressType = {}));
@@ -7,11 +7,11 @@ var ProfileHeaderBannerImageTypes;
7
7
  ProfileHeaderBannerImageTypes["circuit_board"] = "circuit_board";
8
8
  ProfileHeaderBannerImageTypes["hidden"] = "hidden";
9
9
  ProfileHeaderBannerImageTypes["asset"] = "asset";
10
- })(ProfileHeaderBannerImageTypes = exports.ProfileHeaderBannerImageTypes || (exports.ProfileHeaderBannerImageTypes = {}));
10
+ })(ProfileHeaderBannerImageTypes || (exports.ProfileHeaderBannerImageTypes = ProfileHeaderBannerImageTypes = {}));
11
11
  var ProfileHeaderPFPImageTypes;
12
12
  (function (ProfileHeaderPFPImageTypes) {
13
13
  ProfileHeaderPFPImageTypes["personalized_handle"] = "personalized_handle";
14
14
  ProfileHeaderPFPImageTypes["pfp"] = "pfp";
15
15
  ProfileHeaderPFPImageTypes["hidden"] = "hidden";
16
16
  ProfileHeaderPFPImageTypes["asset"] = "asset";
17
- })(ProfileHeaderPFPImageTypes = exports.ProfileHeaderPFPImageTypes || (exports.ProfileHeaderPFPImageTypes = {}));
17
+ })(ProfileHeaderPFPImageTypes || (exports.ProfileHeaderPFPImageTypes = ProfileHeaderPFPImageTypes = {}));
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  export { designerSchema } from './schema/designer';
4
2
  export { handleDatumSchema } from './schema/handleData';
5
3
  export { marketplaceDatumSchema } from './schema/marketplaceDatum';
@@ -44,8 +42,8 @@ declare class JsonToDatumObject {
44
42
  json: any;
45
43
  options: EncodeOptions;
46
44
  constructor(json: any, options?: EncodeOptions);
47
- getFormattedKey: (key: string) => string | number | Buffer;
48
- getHexOrString: (str: string) => string | Buffer;
45
+ getFormattedKey: (key: string) => string | number | Buffer<ArrayBuffer>;
46
+ getHexOrString: (str: string) => string | Buffer<ArrayBuffer>;
49
47
  encodeCBOR: (encoder: any) => any;
50
48
  keyIsNumeric: (key: any) => boolean | undefined;
51
49
  }
@@ -57,6 +55,6 @@ export declare const encodeJsonToDatum: (json: any, options?: EncodeOptions) =>
57
55
  export declare const decodeCborToJson: ({ cborString, schema, defaultKeyType, forJson }: {
58
56
  cborString: string;
59
57
  schema?: any;
60
- defaultKeyType?: DefaultTextFormat | undefined;
61
- forJson?: boolean | undefined;
58
+ defaultKeyType?: DefaultTextFormat;
59
+ forJson?: boolean;
62
60
  }) => any;
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  Object.defineProperty(exports, "__esModule", { value: true });
26
36
  exports.decodeCborToJson = exports.encodeJsonToDatum = exports.DupeKey = exports.DefaultTextFormat = exports.subHandleSettingsDatumSchema = exports.socialsSchema = exports.portalSchema = exports.marketplaceDatumSchema = exports.handleDatumSchema = exports.designerSchema = void 0;
27
37
  const boolean_1 = require("boolean");
@@ -53,7 +63,7 @@ var DefaultTextFormat;
53
63
  (function (DefaultTextFormat) {
54
64
  DefaultTextFormat["UTF8"] = "utf8";
55
65
  DefaultTextFormat["HEX"] = "hex";
56
- })(DefaultTextFormat = exports.DefaultTextFormat || (exports.DefaultTextFormat = {}));
66
+ })(DefaultTextFormat || (exports.DefaultTextFormat = DefaultTextFormat = {}));
57
67
  class JsonToDatumObject {
58
68
  constructor(json, options) {
59
69
  var _a, _b;
@@ -1,5 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
1
  import { AddressDetails, AddressType, AssetNameLabel } from '../../types';
4
2
  export declare const getNativeCrypto: () => Promise<any>;
5
3
  export declare function dec2hex(dec: number): string;
@@ -18,8 +16,8 @@ export declare const getPaymentAddressType: (headerByte: number) => AddressType;
18
16
  export declare const buildPaymentAddressType: (address: string) => AddressType;
19
17
  export declare const buildStakeKey: (address: string) => string | null;
20
18
  export declare const getPaymentKeyHash: (address: string) => string | null;
21
- export declare const bech32FromHex: (hex: string, isTestnet?: boolean, type?: 'addr' | 'stake' | 'pool' | 'drep' | 'cc_hot' | 'cc_cold') => string;
22
- export declare const bech32AddressFromHashes: (paymentHash: string, paymentHashType?: 'key' | 'script', stakeHash?: string, stakeHashType?: 'key' | 'script', type?: 'addr' | 'stake', isTestnet?: boolean) => string;
19
+ export declare const bech32FromHex: (hex: string, isTestnet?: boolean, type?: "addr" | "stake" | "pool" | "drep" | "cc_hot" | "cc_cold") => string;
20
+ export declare const bech32AddressFromHashes: (paymentHash: string, paymentHashType?: "key" | "script", stakeHash?: string, stakeHashType?: "key" | "script", type?: "addr" | "stake", isTestnet?: boolean) => string;
23
21
  export declare const buildHolderInfo: (addr: string) => AddressDetails;
24
22
  export declare const getDateStringFromSlot: (currentSlot: number) => Date;
25
23
  export declare const getSlotNumberFromDate: (date: Date) => number;
@@ -15,18 +15,32 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
37
  };
28
38
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.blake2b = exports.addressHexToBech32 = exports.getSlotNumberFromDate = exports.getDateStringFromSlot = exports.buildHolderInfo = exports.bech32AddressFromHashes = exports.bech32FromHex = exports.getPaymentKeyHash = exports.buildStakeKey = exports.buildPaymentAddressType = exports.getPaymentAddressType = exports.checkNameLabel = exports.parseAssetNameLabel = exports.decodeAddress = exports.getChallengeFromVerifier = exports.base64urlencode = exports.sha256 = exports.getRandomCodeVerifier = exports.dec2hex = exports.getNativeCrypto = void 0;
39
+ exports.blake2b = exports.addressHexToBech32 = exports.getSlotNumberFromDate = exports.getDateStringFromSlot = exports.buildHolderInfo = exports.bech32AddressFromHashes = exports.bech32FromHex = exports.getPaymentKeyHash = exports.buildStakeKey = exports.buildPaymentAddressType = exports.getPaymentAddressType = exports.checkNameLabel = exports.parseAssetNameLabel = exports.decodeAddress = exports.sha256 = exports.getNativeCrypto = void 0;
40
+ exports.dec2hex = dec2hex;
41
+ exports.getRandomCodeVerifier = getRandomCodeVerifier;
42
+ exports.base64urlencode = base64urlencode;
43
+ exports.getChallengeFromVerifier = getChallengeFromVerifier;
30
44
  const bech32_1 = require("bech32");
31
45
  const blakejs_1 = require("blakejs");
32
46
  const bs58_1 = __importDefault(require("bs58"));
@@ -48,14 +62,12 @@ exports.getNativeCrypto = getNativeCrypto;
48
62
  function dec2hex(dec) {
49
63
  return ('0' + dec.toString(16)).slice(-2);
50
64
  }
51
- exports.dec2hex = dec2hex;
52
65
  async function getRandomCodeVerifier(length) {
53
66
  const crypto = await (0, exports.getNativeCrypto)();
54
67
  const array = new Uint32Array(length / 2);
55
68
  crypto.getRandomValues(array);
56
69
  return Array.from(array, dec2hex).join('');
57
70
  }
58
- exports.getRandomCodeVerifier = getRandomCodeVerifier;
59
71
  const sha256 = async (plain) => {
60
72
  const crypto = await (0, exports.getNativeCrypto)();
61
73
  const encoder = new TextEncoder();
@@ -75,20 +87,18 @@ function base64urlencode(a) {
75
87
  .replace(/\//g, '_')
76
88
  .replace(/=+$/, '');
77
89
  }
78
- exports.base64urlencode = base64urlencode;
79
90
  async function getChallengeFromVerifier(verifier) {
80
91
  const hashed = await (0, exports.sha256)(verifier);
81
92
  const base64encoded = base64urlencode(hashed);
82
93
  return base64encoded;
83
94
  }
84
- exports.getChallengeFromVerifier = getChallengeFromVerifier;
85
95
  const decodeAddress = (address) => {
86
96
  try {
87
97
  const addressWords = bech32_1.bech32.decode(address, address.length);
88
98
  const payload = bech32_1.bech32.fromWords(addressWords.words);
89
99
  return `${Buffer.from(payload).toString('hex')}`;
90
100
  }
91
- catch (error) {
101
+ catch (_a) {
92
102
  return null;
93
103
  }
94
104
  };
package/utils/index.d.ts CHANGED
@@ -13,18 +13,18 @@ export declare const getElapsedTime: (milliseconds: number) => string;
13
13
  export declare const objectHasKeys: (o: any) => boolean;
14
14
  export declare const isEmpty: (obj: any) => boolean;
15
15
  export declare const isObject: (o: any) => boolean;
16
- export declare const hasOwnProperty: (o: any, v: PropertyKey) => boolean;
17
- export declare const isDate: (d: any) => boolean;
16
+ export declare const hasOwnProperty: (o: any, ...args: [v: PropertyKey]) => boolean;
17
+ export declare const isDate: (d: any) => d is Date;
18
18
  export declare const isEmptyObject: (o: any) => boolean;
19
19
  export declare const makeObjectWithoutPrototype: () => any;
20
- export declare const ExcludesFalse: <T>(n?: T | null | undefined) => n is T;
20
+ export declare const ExcludesFalse: <T>(n?: T | undefined | null) => n is T;
21
21
  export declare const diff: (lhs: any, rhs: any) => any;
22
22
  export declare const mapStringifyReplacer: (_key: any, value: any) => any;
23
23
  export declare const mapNoKeysStringifyReplacer: (_key: any, value: any) => any;
24
24
  export declare const USER_ISSUE_TRACKING_ID_REGEX: RegExp;
25
25
  export declare const createUserIssueTrackingId: ({ timestamp, random }?: {
26
- timestamp?: number | undefined;
27
- random?: (() => number) | undefined;
26
+ timestamp?: number;
27
+ random?: () => number;
28
28
  }) => string;
29
29
  export declare const isUserIssueTrackingId: (value: unknown) => value is string;
30
30
  export declare const normalizeUserIssueEventSegment: (value: string) => string;