@elimeleth/vct-flow
Version:
Crea un archivo app.ts, coloca el codigo de abajo alli y luego puedes correrlo con `npx tsx src/app.ts`
1,877 lines (1,834 loc) โข 4.79 MB
JavaScript
'use strict';
require('reflect-metadata');
var fs$t = require('node:fs/promises');
var path$s = require('node:path');
var crypto$9 = require('crypto');
var tty = require('node:tty');
var util$q = require('node:util');
var require$$0$6 = require('os');
var path$r = require('path');
var require$$0$7 = require('util');
var require$$0$8 = require('stream');
var require$$0$a = require('events');
var require$$0$9 = require('fs');
var node_url = require('node:url');
var require$$0$c = require('buffer');
var require$$0$b = require('tty');
var fs$u = require('fs/promises');
var http$3 = require('http');
var https$3 = require('https');
var require$$0$d = require('url');
var zlib$4 = require('zlib');
var require$$1$1 = require('string_decoder');
var vctAssistants = require('@elimeleth/vct-assistants');
var prompts = require('@langchain/core/prompts');
var output_parsers = require('langchain/output_parsers');
var z = require('zod');
var require$$2$3 = require('child_process');
var typeorm = require('typeorm');
var typeormExtension = require('typeorm-extension');
var dateFns = require('date-fns');
var require$$7$1 = require('net');
var require$$4$1 = require('dns');
var require$$1$2 = require('tls');
var require$$0$e = require('constants');
var require$$5$1 = require('assert');
var require$$8 = require('querystring');
var polka = require('polka');
function coerce(o) {
if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') {
return o;
}
if (o instanceof ArrayBuffer) {
return new Uint8Array(o);
}
if (ArrayBuffer.isView(o)) {
return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
}
throw new Error('Unknown type, must be binary type');
}
function fromString$1(str) {
return new TextEncoder().encode(str);
}
function toString$7(b) {
return new TextDecoder().decode(b);
}
/* eslint-disable */
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
/**
* @param {string} ALPHABET
* @param {any} name
*/
function base$1(ALPHABET, name) {
if (ALPHABET.length >= 255) {
throw new TypeError('Alphabet too long');
}
var BASE_MAP = new Uint8Array(256);
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255;
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i);
var xc = x.charCodeAt(0);
if (BASE_MAP[xc] !== 255) {
throw new TypeError(x + ' is ambiguous');
}
BASE_MAP[xc] = i;
}
var BASE = ALPHABET.length;
var LEADER = ALPHABET.charAt(0);
var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
/**
* @param {any[] | Iterable<number>} source
*/
function encode(source) {
// @ts-ignore
if (source instanceof Uint8Array)
;
else if (ArrayBuffer.isView(source)) {
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
}
else if (Array.isArray(source)) {
source = Uint8Array.from(source);
}
if (!(source instanceof Uint8Array)) {
throw new TypeError('Expected Uint8Array');
}
if (source.length === 0) {
return '';
}
// Skip & count leading zeroes.
var zeroes = 0;
var length = 0;
var pbegin = 0;
var pend = source.length;
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
var b58 = new Uint8Array(size);
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin];
// Apply "b58 = b58 * 256 + ch".
var i = 0;
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0;
b58[it1] = (carry % BASE) >>> 0;
carry = (carry / BASE) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
var it2 = size - length;
while (it2 !== size && b58[it2] === 0) {
it2++;
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes);
for (; it2 < size; ++it2) {
str += ALPHABET.charAt(b58[it2]);
}
return str;
}
/**
* @param {string | string[]} source
*/
function decodeUnsafe(source) {
if (typeof source !== 'string') {
throw new TypeError('Expected String');
}
if (source.length === 0) {
return new Uint8Array();
}
var psz = 0;
// Skip leading spaces.
if (source[psz] === ' ') {
return;
}
// Skip and count leading '1's.
var zeroes = 0;
var length = 0;
while (source[psz] === LEADER) {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size);
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)];
// Invalid character
if (carry === 255) {
return;
}
var i = 0;
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0;
b256[it3] = (carry % 256) >>> 0;
carry = (carry / 256) >>> 0;
}
if (carry !== 0) {
throw new Error('Non-zero carry');
}
length = i;
psz++;
}
// Skip trailing spaces.
if (source[psz] === ' ') {
return;
}
// Skip leading zeroes in b256.
var it4 = size - length;
while (it4 !== size && b256[it4] === 0) {
it4++;
}
var vch = new Uint8Array(zeroes + (size - it4));
var j = zeroes;
while (it4 !== size) {
vch[j++] = b256[it4++];
}
return vch;
}
/**
* @param {string | string[]} string
*/
function decode(string) {
var buffer = decodeUnsafe(string);
if (buffer) {
return buffer;
}
throw new Error(`Non-${name} character`);
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
};
}
var src$5 = base$1;
var _brrp__multiformats_scope_baseX = src$5;
/**
* Class represents both BaseEncoder and MultibaseEncoder meaning it
* can be used to encode to multibase or base encode without multibase
* prefix.
*/
class Encoder$2 {
name;
prefix;
baseEncode;
constructor(name, prefix, baseEncode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
}
encode(bytes) {
if (bytes instanceof Uint8Array) {
return `${this.prefix}${this.baseEncode(bytes)}`;
}
else {
throw Error('Unknown type, must be binary type');
}
}
}
/**
* Class represents both BaseDecoder and MultibaseDecoder so it could be used
* to decode multibases (with matching prefix) or just base decode strings
* with corresponding base encoding.
*/
class Decoder {
name;
prefix;
baseDecode;
prefixCodePoint;
constructor(name, prefix, baseDecode) {
this.name = name;
this.prefix = prefix;
const prefixCodePoint = prefix.codePointAt(0);
/* c8 ignore next 3 */
if (prefixCodePoint === undefined) {
throw new Error('Invalid prefix character');
}
this.prefixCodePoint = prefixCodePoint;
this.baseDecode = baseDecode;
}
decode(text) {
if (typeof text === 'string') {
if (text.codePointAt(0) !== this.prefixCodePoint) {
throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
}
return this.baseDecode(text.slice(this.prefix.length));
}
else {
throw Error('Can only multibase decode strings');
}
}
or(decoder) {
return or(this, decoder);
}
}
class ComposedDecoder {
decoders;
constructor(decoders) {
this.decoders = decoders;
}
or(decoder) {
return or(this, decoder);
}
decode(input) {
const prefix = input[0];
const decoder = this.decoders[prefix];
if (decoder != null) {
return decoder.decode(input);
}
else {
throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
}
}
}
function or(left, right) {
return new ComposedDecoder({
...(left.decoders ?? { [left.prefix]: left }),
...(right.decoders ?? { [right.prefix]: right })
});
}
class Codec {
name;
prefix;
baseEncode;
baseDecode;
encoder;
decoder;
constructor(name, prefix, baseEncode, baseDecode) {
this.name = name;
this.prefix = prefix;
this.baseEncode = baseEncode;
this.baseDecode = baseDecode;
this.encoder = new Encoder$2(name, prefix, baseEncode);
this.decoder = new Decoder(name, prefix, baseDecode);
}
encode(input) {
return this.encoder.encode(input);
}
decode(input) {
return this.decoder.decode(input);
}
}
function from({ name, prefix, encode, decode }) {
return new Codec(name, prefix, encode, decode);
}
function baseX({ name, prefix, alphabet }) {
const { encode, decode } = _brrp__multiformats_scope_baseX(alphabet, name);
return from({
prefix,
name,
encode,
decode: (text) => coerce(decode(text))
});
}
function decode$2(string, alphabetIdx, bitsPerChar, name) {
// Count the padding bytes:
let end = string.length;
while (string[end - 1] === '=') {
--end;
}
// Allocate the output:
const out = new Uint8Array((end * bitsPerChar / 8) | 0);
// Parse the data:
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
let written = 0; // Next byte to write
for (let i = 0; i < end; ++i) {
// Read one character from the string:
const value = alphabetIdx[string[i]];
if (value === undefined) {
throw new SyntaxError(`Non-${name} character`);
}
// Append the bits to the buffer:
buffer = (buffer << bitsPerChar) | value;
bits += bitsPerChar;
// Write out some bits if the buffer has a byte's worth:
if (bits >= 8) {
bits -= 8;
out[written++] = 0xff & (buffer >> bits);
}
}
// Verify that we have received just enough bits:
if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {
throw new SyntaxError('Unexpected end of data');
}
return out;
}
function encode$6(data, alphabet, bitsPerChar) {
const pad = alphabet[alphabet.length - 1] === '=';
const mask = (1 << bitsPerChar) - 1;
let out = '';
let bits = 0; // Number of bits currently in the buffer
let buffer = 0; // Bits waiting to be written out, MSB first
for (let i = 0; i < data.length; ++i) {
// Slurp data into the buffer:
buffer = (buffer << 8) | data[i];
bits += 8;
// Write out as much as we can:
while (bits > bitsPerChar) {
bits -= bitsPerChar;
out += alphabet[mask & (buffer >> bits)];
}
}
// Partial character:
if (bits !== 0) {
out += alphabet[mask & (buffer << (bitsPerChar - bits))];
}
// Add padding characters until we hit a byte boundary:
if (pad) {
while (((out.length * bitsPerChar) & 7) !== 0) {
out += '=';
}
}
return out;
}
function createAlphabetIdx(alphabet) {
// Build the character lookup table:
const alphabetIdx = {};
for (let i = 0; i < alphabet.length; ++i) {
alphabetIdx[alphabet[i]] = i;
}
return alphabetIdx;
}
/**
* RFC4648 Factory
*/
function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
const alphabetIdx = createAlphabetIdx(alphabet);
return from({
prefix,
name,
encode(input) {
return encode$6(input, alphabet, bitsPerChar);
},
decode(input) {
return decode$2(input, alphabetIdx, bitsPerChar, name);
}
});
}
const base10 = baseX({
prefix: '9',
name: 'base10',
alphabet: '0123456789'
});
var base10$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base10: base10
});
const base16 = rfc4648({
prefix: 'f',
name: 'base16',
alphabet: '0123456789abcdef',
bitsPerChar: 4
});
const base16upper = rfc4648({
prefix: 'F',
name: 'base16upper',
alphabet: '0123456789ABCDEF',
bitsPerChar: 4
});
var base16$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base16: base16,
base16upper: base16upper
});
const base2 = rfc4648({
prefix: '0',
name: 'base2',
alphabet: '01',
bitsPerChar: 1
});
var base2$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base2: base2
});
const alphabet = Array.from('๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ');
const alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));
const alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {
const codePoint = c.codePointAt(0);
if (codePoint == null) {
throw new Error(`Invalid character: ${c}`);
}
p[codePoint] = i;
return p;
}, ([])));
function encode$5(data) {
return data.reduce((p, c) => {
p += alphabetBytesToChars[c];
return p;
}, '');
}
function decode$1(str) {
const byts = [];
for (const char of str) {
const codePoint = char.codePointAt(0);
if (codePoint == null) {
throw new Error(`Invalid character: ${char}`);
}
const byt = alphabetCharsToBytes[codePoint];
if (byt == null) {
throw new Error(`Non-base256emoji character: ${char}`);
}
byts.push(byt);
}
return new Uint8Array(byts);
}
const base256emoji = from({
prefix: '๐',
name: 'base256emoji',
encode: encode$5,
decode: decode$1
});
var base256emoji$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base256emoji: base256emoji
});
const base32 = rfc4648({
prefix: 'b',
name: 'base32',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567',
bitsPerChar: 5
});
const base32upper = rfc4648({
prefix: 'B',
name: 'base32upper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
bitsPerChar: 5
});
const base32pad = rfc4648({
prefix: 'c',
name: 'base32pad',
alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',
bitsPerChar: 5
});
const base32padupper = rfc4648({
prefix: 'C',
name: 'base32padupper',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',
bitsPerChar: 5
});
const base32hex = rfc4648({
prefix: 'v',
name: 'base32hex',
alphabet: '0123456789abcdefghijklmnopqrstuv',
bitsPerChar: 5
});
const base32hexupper = rfc4648({
prefix: 'V',
name: 'base32hexupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',
bitsPerChar: 5
});
const base32hexpad = rfc4648({
prefix: 't',
name: 'base32hexpad',
alphabet: '0123456789abcdefghijklmnopqrstuv=',
bitsPerChar: 5
});
const base32hexpadupper = rfc4648({
prefix: 'T',
name: 'base32hexpadupper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',
bitsPerChar: 5
});
const base32z = rfc4648({
prefix: 'h',
name: 'base32z',
alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',
bitsPerChar: 5
});
var base32$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base32: base32,
base32upper: base32upper,
base32pad: base32pad,
base32padupper: base32padupper,
base32hex: base32hex,
base32hexupper: base32hexupper,
base32hexpad: base32hexpad,
base32hexpadupper: base32hexpadupper,
base32z: base32z
});
const base36 = baseX({
prefix: 'k',
name: 'base36',
alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'
});
const base36upper = baseX({
prefix: 'K',
name: 'base36upper',
alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
});
var base36$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base36: base36,
base36upper: base36upper
});
const base58btc = baseX({
name: 'base58btc',
prefix: 'z',
alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
});
const base58flickr = baseX({
name: 'base58flickr',
prefix: 'Z',
alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
});
var base58 = /*#__PURE__*/Object.freeze({
__proto__: null,
base58btc: base58btc,
base58flickr: base58flickr
});
const base64$5 = rfc4648({
prefix: 'm',
name: 'base64',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
bitsPerChar: 6
});
const base64pad = rfc4648({
prefix: 'M',
name: 'base64pad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
bitsPerChar: 6
});
const base64url = rfc4648({
prefix: 'u',
name: 'base64url',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
bitsPerChar: 6
});
const base64urlpad = rfc4648({
prefix: 'U',
name: 'base64urlpad',
alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',
bitsPerChar: 6
});
var base64$6 = /*#__PURE__*/Object.freeze({
__proto__: null,
base64: base64$5,
base64pad: base64pad,
base64url: base64url,
base64urlpad: base64urlpad
});
const base8 = rfc4648({
prefix: '7',
name: 'base8',
alphabet: '01234567',
bitsPerChar: 3
});
var base8$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
base8: base8
});
const identity = from({
prefix: '\x00',
name: 'identity',
encode: (buf) => toString$7(buf),
decode: (str) => fromString$1(str)
});
var identityBase = /*#__PURE__*/Object.freeze({
__proto__: null,
identity: identity
});
new TextEncoder();
new TextDecoder();
const bases = { ...identityBase, ...base2$1, ...base8$1, ...base10$1, ...base16$1, ...base32$1, ...base36$1, ...base58, ...base64$6, ...base256emoji$1 };
/**
* Returns a `Uint8Array` of the requested size. Referenced memory will
* be initialized to 0.
*/
/**
* Where possible returns a Uint8Array of the requested size that references
* uninitialized memory. Only use if you are certain you will immediately
* overwrite every value in the returned `Uint8Array`.
*/
function allocUnsafe(size = 0) {
return new Uint8Array(size);
}
function createCodec(name, prefix, encode, decode) {
return {
name,
prefix,
encoder: {
name,
prefix,
encode
},
decoder: {
decode
}
};
}
const string$2 = createCodec('utf8', 'u', (buf) => {
const decoder = new TextDecoder('utf8');
return 'u' + decoder.decode(buf);
}, (str) => {
const encoder = new TextEncoder();
return encoder.encode(str.substring(1));
});
const ascii$1 = createCodec('ascii', 'a', (buf) => {
let string = 'a';
for (let i = 0; i < buf.length; i++) {
string += String.fromCharCode(buf[i]);
}
return string;
}, (str) => {
str = str.substring(1);
const buf = allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
});
const BASES = {
utf8: string$2,
'utf-8': string$2,
hex: bases.base16,
latin1: ascii$1,
ascii: ascii$1,
binary: ascii$1,
...bases
};
/**
* Create a `Uint8Array` from the passed string
*
* Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.
*
* Also `ascii` which is similar to node's 'binary' encoding.
*/
function fromString(string, encoding = 'utf8') {
const base = BASES[encoding];
if (base == null) {
throw new Error(`Unsupported encoding "${encoding}"`);
}
// add multibase prefix
return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions
}
/**
* Turns a `Uint8Array` into a string.
*
* Supports `utf8`, `utf-8` and any encoding supported by the multibase module.
*
* Also `ascii` which is similar to node's 'binary' encoding.
*/
function toString$6(array, encoding = 'utf8') {
const base = BASES[encoding];
if (base == null) {
throw new Error(`Unsupported encoding "${encoding}"`);
}
// strip multibase prefix
return base.encoder.encode(array).substring(1);
}
const pathSepS = '/';
const pathSepB = new TextEncoder().encode(pathSepS);
const pathSep = pathSepB[0];
/**
* A Key represents the unique identifier of an object.
* Our Key scheme is inspired by file systems and Google App Engine key model.
* Keys are meant to be unique across a system. Keys are hierarchical,
* incorporating more and more specific namespaces. Thus keys can be deemed
* 'children' or 'ancestors' of other keys:
* - `new Key('/Comedy')`
* - `new Key('/Comedy/MontyPython')`
* Also, every namespace can be parametrized to embed relevant object
* information. For example, the Key `name` (most specific namespace) could
* include the object type:
* - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`
* - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`
* - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`
*
*/
class Key {
_buf;
/**
* @param {string | Uint8Array} s
* @param {boolean} [clean]
*/
constructor(s, clean) {
if (typeof s === 'string') {
this._buf = fromString(s);
}
else if (s instanceof Uint8Array) {
this._buf = s;
}
else {
throw new Error('Invalid key, should be String of Uint8Array');
}
if (clean == null) {
clean = true;
}
if (clean) {
this.clean();
}
if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {
throw new Error('Invalid key');
}
}
/**
* Convert to the string representation
*
* @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
* @returns {string}
*/
toString(encoding = 'utf8') {
return toString$6(this._buf, encoding);
}
/**
* Return the Uint8Array representation of the key
*
* @returns {Uint8Array}
*/
uint8Array() {
return this._buf;
}
/**
* Return string representation of the key
*
* @returns {string}
*/
get [Symbol.toStringTag]() {
return `Key(${this.toString()})`;
}
/**
* Constructs a key out of a namespace array.
*
* @param {Array<string>} list - The array of namespaces
* @returns {Key}
*
* @example
* ```js
* Key.withNamespaces(['one', 'two'])
* // => Key('/one/two')
* ```
*/
static withNamespaces(list) {
return new Key(list.join(pathSepS));
}
/**
* Returns a randomly (uuid) generated key.
*
* @returns {Key}
*
* @example
* ```js
* Key.random()
* // => Key('/344502982398')
* ```
*/
static random() {
return new Key(Math.random().toString().substring(2));
}
/**
* @param {*} other
*/
static asKey(other) {
if (other instanceof Uint8Array || typeof other === 'string') {
// we can create a key from this
return new Key(other);
}
if (typeof other.uint8Array === 'function') {
// this is an older version or may have crossed the esm/cjs boundary
return new Key(other.uint8Array());
}
return null;
}
/**
* Cleanup the current key
*
* @returns {void}
*/
clean() {
if (this._buf == null || this._buf.byteLength === 0) {
this._buf = pathSepB;
}
if (this._buf[0] !== pathSep) {
const bytes = new Uint8Array(this._buf.byteLength + 1);
bytes.fill(pathSep, 0, 1);
bytes.set(this._buf, 1);
this._buf = bytes;
}
// normalize does not remove trailing slashes
while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {
this._buf = this._buf.subarray(0, -1);
}
}
/**
* Check if the given key is sorted lower than ourself.
*
* @param {Key} key - The other Key to check against
* @returns {boolean}
*/
less(key) {
const list1 = this.list();
const list2 = key.list();
for (let i = 0; i < list1.length; i++) {
if (list2.length < i + 1) {
return false;
}
const c1 = list1[i];
const c2 = list2[i];
if (c1 < c2) {
return true;
}
else if (c1 > c2) {
return false;
}
}
return list1.length < list2.length;
}
/**
* Returns the key with all parts in reversed order.
*
* @returns {Key}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()
* // => Key('/Actor:JohnCleese/MontyPython/Comedy')
* ```
*/
reverse() {
return Key.withNamespaces(this.list().slice().reverse());
}
/**
* Returns the `namespaces` making up this Key.
*
* @returns {Array<string>}
*/
namespaces() {
return this.list();
}
/** Returns the "base" namespace of this key.
*
* @returns {string}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()
* // => 'Actor:JohnCleese'
* ```
*/
baseNamespace() {
const ns = this.namespaces();
return ns[ns.length - 1];
}
/**
* Returns the `list` representation of this key.
*
* @returns {Array<string>}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
* // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
* ```
*/
list() {
return this.toString().split(pathSepS).slice(1);
}
/**
* Returns the "type" of this key (value of last namespace).
*
* @returns {string}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').type()
* // => 'Actor'
* ```
*/
type() {
return namespaceType(this.baseNamespace());
}
/**
* Returns the "name" of this key (field of last namespace).
*
* @returns {string}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').name()
* // => 'JohnCleese'
* ```
*/
name() {
return namespaceValue(this.baseNamespace());
}
/**
* Returns an "instance" of this type key (appends value to namespace).
*
* @param {string} s - The string to append.
* @returns {Key}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')
* // => Key('/Comedy/MontyPython/Actor:JohnCleese')
* ```
*/
instance(s) {
return new Key(this.toString() + ':' + s);
}
/**
* Returns the "path" of this key (parent + type).
*
* @returns {Key}
*
* @example
* ```js
* new Key('/Comedy/MontyPython/Actor:JohnCleese').path()
* // => Key('/Comedy/MontyPython/Actor')
* ```
*/
path() {
let p = this.parent().toString();
if (!p.endsWith(pathSepS)) {
p += pathSepS;
}
p += this.type();
return new Key(p);
}
/**
* Returns the `parent` Key of this Key.
*
* @returns {Key}
*
* @example
* ```js
* new Key("/Comedy/MontyPython/Actor:JohnCleese").parent()
* // => Key("/Comedy/MontyPython")
* ```
*/
parent() {
const list = this.list();
if (list.length === 1) {
return new Key(pathSepS);
}
return new Key(list.slice(0, -1).join(pathSepS));
}
/**
* Returns the `child` Key of this Key.
*
* @param {Key} key - The child Key to add
* @returns {Key}
*
* @example
* ```js
* new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))
* // => Key('/Comedy/MontyPython/Actor:JohnCleese')
* ```
*/
child(key) {
if (this.toString() === pathSepS) {
return key;
}
else if (key.toString() === pathSepS) {
return this;
}
return new Key(this.toString() + key.toString(), false);
}
/**
* Returns whether this key is a prefix of `other`
*
* @param {Key} other - The other key to test against
* @returns {boolean}
*
* @example
* ```js
* new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')
* // => true
* ```
*/
isAncestorOf(other) {
if (other.toString() === this.toString()) {
return false;
}
return other.toString().startsWith(this.toString());
}
/**
* Returns whether this key is a contains another as prefix.
*
* @param {Key} other - The other Key to test against
* @returns {boolean}
*
* @example
* ```js
* new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')
* // => true
* ```
*/
isDecendantOf(other) {
if (other.toString() === this.toString()) {
return false;
}
return this.toString().startsWith(other.toString());
}
/**
* Checks if this key has only one namespace.
*
* @returns {boolean}
*/
isTopLevel() {
return this.list().length === 1;
}
/**
* Concats one or more Keys into one new Key.
*
* @param {Array<Key>} keys - The array of keys to concatenate
* @returns {Key}
*/
concat(...keys) {
return Key.withNamespaces([...this.namespaces(), ...flatten$4(keys.map(key => key.namespaces()))]);
}
}
/**
* The first component of a namespace. `foo` in `foo:bar`
*
* @param {string} ns
* @returns {string}
*/
function namespaceType(ns) {
const parts = ns.split(':');
if (parts.length < 2) {
return '';
}
return parts.slice(0, -1).join(':');
}
/**
* The last component of a namespace, `baz` in `foo:bar:baz`.
*
* @param {string} ns
* @returns {string}
*/
function namespaceValue(ns) {
const parts = ns.split(':');
return parts[parts.length - 1];
}
/**
* Flatten array of arrays (only one level)
*
* @template T
* @param {Array<any>} arr
* @returns {T[]}
*/
function flatten$4(arr) {
return ([]).concat(...arr);
}
const SHARDING_FN = 'SHARDING';
/**
* @packageDocumentation
*
* Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.
*
* @example
*
* ```javascript
* import drain from 'it-drain'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* drain(values)
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import drain from 'it-drain'
*
* const values = async function * {
* yield * [0, 1, 2, 3, 4]
* }
*
* await drain(values())
* ```
*/
function isAsyncIterable$7(thing) {
return thing[Symbol.asyncIterator] != null;
}
function drain(source) {
if (isAsyncIterable$7(source)) {
return (async () => {
for await (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars
})();
}
else {
for (const _ of source) { } // eslint-disable-line no-empty,@typescript-eslint/no-unused-vars
}
}
/**
* @packageDocumentation
*
* Lets you look at the contents of an async iterator and decide what to do
*
* @example
*
* ```javascript
* import peekable from 'it-peekable'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* const it = peekable(value)
*
* const first = it.peek()
*
* console.info(first) // 0
*
* it.push(first)
*
* console.info([...it])
* // [ 0, 1, 2, 3, 4 ]
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import peekable from 'it-peekable'
*
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const it = peekable(values())
*
* const first = await it.peek()
*
* console.info(first) // 0
*
* it.push(first)
*
* console.info(await all(it))
* // [ 0, 1, 2, 3, 4 ]
* ```
*/
function peekable(iterable) {
// @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable
const [iterator, symbol] = iterable[Symbol.asyncIterator] != null
// @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable
? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]
// @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable
: [iterable[Symbol.iterator](), Symbol.iterator];
const queue = [];
// @ts-expect-error can't use symbol to index peekable
return {
peek: () => {
return iterator.next();
},
push: (value) => {
queue.push(value);
},
next: () => {
if (queue.length > 0) {
return {
done: false,
value: queue.shift()
};
}
return iterator.next();
},
[symbol]() {
return this;
}
};
}
/**
* @packageDocumentation
*
* Filter values out of an (async)iterable
*
* @example
*
* ```javascript
* import all from 'it-all'
* import filter from 'it-filter'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* const fn = (val, index) => val > 2 // Return boolean to keep item
*
* const arr = all(filter(values, fn))
*
* console.info(arr) // 3, 4
* ```
*
* Async sources and filter functions must be awaited:
*
* ```javascript
* import all from 'it-all'
* import filter from 'it-filter'
*
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item
*
* const arr = await all(filter(values, fn))
*
* console.info(arr) // 3, 4
* ```
*/
function isAsyncIterable$6(thing) {
return thing[Symbol.asyncIterator] != null;
}
function filter$3(source, fn) {
let index = 0;
if (isAsyncIterable$6(source)) {
return (async function* () {
for await (const entry of source) {
if (await fn(entry, index++)) {
yield entry;
}
}
})();
}
// if mapping function returns a promise we have to return an async generator
const peekable$1 = peekable(source);
const { value, done } = peekable$1.next();
if (done === true) {
return (function* () { }());
}
const res = fn(value, index++);
// @ts-expect-error .then is not present on O
if (typeof res.then === 'function') {
return (async function* () {
if (await res) {
yield value;
}
for (const entry of peekable$1) {
if (await fn(entry, index++)) {
yield entry;
}
}
})();
}
const func = fn;
return (function* () {
if (res === true) {
yield value;
}
for (const entry of peekable$1) {
if (func(entry, index++)) {
yield entry;
}
}
})();
}
/**
* @packageDocumentation
*
* For when you need a one-liner to collect iterable values.
*
* @example
*
* ```javascript
* import all from 'it-all'
*
* // This can also be an iterator, etc
* const values = function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const arr = all(values)
*
* console.info(arr) // 0, 1, 2, 3, 4
* ```
*
* Async sources must be awaited:
*
* ```javascript
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const arr = await all(values())
*
* console.info(arr) // 0, 1, 2, 3, 4
* ```
*/
function isAsyncIterable$5(thing) {
return thing[Symbol.asyncIterator] != null;
}
function all(source) {
if (isAsyncIterable$5(source)) {
return (async () => {
const arr = [];
for await (const entry of source) {
arr.push(entry);
}
return arr;
})();
}
const arr = [];
for (const entry of source) {
arr.push(entry);
}
return arr;
}
/**
* @packageDocumentation
*
* Consumes all values from an (async)iterable and returns them sorted by the passed sort function.
*
* @example
*
* ```javascript
* import sort from 'it-sort'
* import all from 'it-all'
*
* const sorter = (a, b) => {
* return a.localeCompare(b)
* }
*
* // This can also be an iterator, generator, etc
* const values = ['foo', 'bar']
*
* const arr = all(sort(values, sorter))
*
* console.info(arr) // 'bar', 'foo'
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import sort from 'it-sort'
* import all from 'it-all'
*
* const sorter = (a, b) => {
* return a.localeCompare(b)
* }
*
* const values = async function * () {
* yield * ['foo', 'bar']
* }
*
* const arr = await all(sort(values, sorter))
*
* console.info(arr) // 'bar', 'foo'
* ```
*/
function isAsyncIterable$4(thing) {
return thing[Symbol.asyncIterator] != null;
}
function sort(source, sorter) {
if (isAsyncIterable$4(source)) {
return (async function* () {
const arr = await all(source);
yield* arr.sort(sorter);
})();
}
return (function* () {
const arr = all(source);
yield* arr.sort(sorter);
})();
}
/**
* @packageDocumentation
*
* For when you only want a few values out of an (async)iterable.
*
* @example
*
* ```javascript
* import take from 'it-take'
* import all from 'it-all'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* const arr = all(take(values, 2))
*
* console.info(arr) // 0, 1
* ```
*
* Async sources must be awaited:
*
* ```javascript
* import take from 'it-take'
* import all from 'it-all'
*
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const arr = await all(take(values(), 2))
*
* console.info(arr) // 0, 1
* ```
*/
function isAsyncIterable$3(thing) {
return thing[Symbol.asyncIterator] != null;
}
function take(source, limit) {
if (isAsyncIterable$3(source)) {
return (async function* () {
let items = 0;
if (limit < 1) {
return;
}
for await (const entry of source) {
yield entry;
items++;
if (items === limit) {
return;
}
}
})();
}
return (function* () {
let items = 0;
if (limit < 1) {
return;
}
for (const entry of source) {
yield entry;
items++;
if (items === limit) {
return;
}
}
})();
}
class BaseDatastore {
put(key, val, options) {
return Promise.reject(new Error('.put is not implemented'));
}
get(key, options) {
return Promise.reject(new Error('.get is not implemented'));
}
has(key, options) {
return Promise.reject(new Error('.has is not implemented'));
}
delete(key, options) {
return Promise.reject(new Error('.delete is not implemented'));
}
async *putMany(source, options = {}) {
for await (const { key, value } of source) {
await this.put(key, value, options);
yield key;
}
}
async *getMany(source, options = {}) {
for await (const key of source) {
yield {
key,
value: await this.get(key, options)
};
}
}
async *deleteMany(source, options = {}) {
for await (const key of source) {
await this.delete(key, options);
yield key;
}
}
batch() {
let puts = [];
let dels = [];
return {
put(key, value) {
puts.push({ key, value });
},
delete(key) {
dels.push(key);
},
commit: async (options) => {
await drain(this.putMany(puts, options));
puts = [];
await drain(this.deleteMany(dels, options));
dels = [];
}
};
}
/**
* Extending classes should override `query` or implement this method
*/
// eslint-disable-next-line require-yield
async *_all(q, options) {
throw new Error('._all is not implemented');
}
/**
* Extending classes should override `queryKeys` or implement this method
*/
// eslint-disable-next-line require-yield
async *_allKeys(q, options) {
throw new Error('._allKeys is not implemented');
}
query(q, options) {
let it = this._all(q, options);
if (q.prefix != null) {
const prefix = q.prefix;
it = filter$3(it, (e) => e.key.toString().startsWith(prefix));
}
if (Array.isArray(q.filters)) {
it = q.filters.reduce((it, f) => filter$3(it, f), it);
}
if (Array.isArray(q.orders)) {
it = q.orders.reduce((it, f) => sort(it, f), it);
}
if (q.offset != null) {
let i = 0;
const offset = q.offset;
it = filter$3(it, () => i++ >= offset);
}
if (q.limit != null) {
it = take(it, q.limit);
}
return it;
}
queryKeys(q, options) {
let it = this._allKeys(q, options);
if (q.prefix != null) {
const prefix = q.prefix;
it = filter$3(it, (key) => key.toString().startsWith(prefix));
}
if (Array.isArray(q.filters)) {
it = q.filters.reduce((it, f) => filter$3(it, f), it);
}
if (Array.isArray(q.orders)) {
it = q.orders.reduce((it, f) => sort(it, f), it);
}
if (q.offset != null) {
const offset = q.offset;
let i = 0;
it = filter$3(it, () => i++ >= offset);
}
if (q.limit != null) {
it = take(it, q.limit);
}
return it;
}
}
class OpenFailedError extends Error {
static name = 'OpenFailedError';
static code = 'ERR_OPEN_FAILED';
name = OpenFailedError.name;
code = OpenFailedError.code;
constructor(message = 'Open failed') {
super(message);
}
}
class PutFailedError extends Error {
static name = 'PutFailedError';
static code = 'ERR_PUT_FAILED';
name = PutFailedError.name;
code = PutFailedError.code;
constructor(message = 'Put failed') {
super(message);
}
}
class DeleteFailedError extends Error {
static name = 'DeleteFailedError';
static code = 'ERR_DELETE_FAILED';
name = DeleteFailedError.name;
code = DeleteFailedError.code;
constructor(message = 'Delete failed') {
super(message);
}
}
class NotFoundError extends Error {
static name = 'NotFoundError';
static code = 'ERR_NOT_FOUND';
name = NotFoundError.name;
code = NotFoundError.code;
constructor(message = 'Not Found') {
super(message);
}
}
/**
* @packageDocumentation
*
* Convert one value from an (async)iterator into another.
*
* @example
*
* ```javascript
* import map from 'it-map'
*
* // This can also be an iterator, generator, etc
* const values = [0, 1, 2, 3, 4]
*
* const result = map(values, (val, index) => val++)
*
* console.info(result) // [1, 2, 3, 4, 5]
* ```
*
* Async sources and transforms must be awaited:
*
* ```javascript
* import map from 'it-map'
*
* const values = async function * () {
* yield * [0, 1, 2, 3, 4]
* }
*
* const result = await map(values(), async (val, index) => val++)
*
* console.info(result) // [1, 2, 3, 4, 5]
* ```
*/
function isAsyncIterable$2(thing) {
return thing[Symbol.asyncIterator] != null;
}
function map$3(source, func) {
let index = 0;
if (isAsyncIterable$2(source)) {
return (async function* () {
for await (const val of source) {
yield func(val, index++);
}
})();
}
// if mapping function returns a promise we have to return an async generator
const peekable$1 = peekable(source);
const { value, done } = peekable$1.next();
if (done === true) {
return (function* () { }());
}
const res = func(value, index++);
// @ts-expect-error .then is not present on O
if (typeof res.then === 'function') {
return (async function* () {
yield await res;
for (const val of peekable$1) {
yield func(val, index++);
}
})();
}
const fn = func;
return (function* () {
yield res;
for (const val of peekable$1) {
yield fn(val, index++);
}
})();
}
new Key(SHARDING_FN);
// Helpers.
const s$1 = 1000;
const m = s$1 * 60;
const h = m * 60;
const d = h * 24;
const w = d * 7;
const y = d * 365.25;
function ms$2(value, options) {
try {
if (typeof value === 'string' && value.length > 0) {
return parse$b(value);
}
else if (typeof value === 'number' && isFinite(value)) {
return options?.long ? fmtLong(value) : fmtShort(value);
}
throw new Error('Value is not a string or number.');
}
catch (error) {
const message = isError(error)
? `${error.message}. value=${JSON.stringify(value)}`
: 'An unknown error has occured.';
throw new Error(message);
}
}
/**
* Parse the given `str` and return milliseconds.
*/
function parse$b(str) {
str = String(str);
if (str.length > 100) {
throw new Error('Value exceeds the maximum length of 100 characters.');
}
const match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return NaN;
}
const n = parseFloat(match[1]);
const type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s$1;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
// This should never occur.
throw new Error(`The unit ${type} was matched, but no matching case exists.`);
}
}
/**
* Short format for `ms`.
*/
function fmtShort(ms) {
const msAbs = Math.abs(ms);
if (msAbs >= d) {
return `${Math.round(ms / d)}d`;
}
if (msAbs >= h) {
return `${Math.round(ms / h)}h`;
}
if (msAbs >= m) {
return `${Math.round(ms / m)}m`;
}
if (msAbs >= s$1) {
return `${Math.round(ms / s$1)}s`;
}
return `${ms}ms`;
}
/**
* Long format for `ms`.
*/
function fmtLong(ms) {
const msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs,