flint-orm
Version:
Type-safe SQLite ORM for JavaScript
1,666 lines (1,635 loc) • 190 kB
JavaScript
// @bun
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
var canCache = mod != null && typeof mod === "object";
if (canCache) {
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
var cached = cache.get(mod);
if (cached)
return cached;
}
target = mod != null ? __create(__getProtoOf(mod)) : {};
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
for (let key of __getOwnPropNames(mod))
if (!__hasOwnProp.call(to, key))
__defProp(to, key, {
get: __accessProp.bind(mod, key),
enumerable: true
});
if (canCache)
cache.set(mod, to);
return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: __exportSetter.bind(all, name)
});
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;
// node_modules/@libsql/core/lib-esm/api.js
var LibsqlError, LibsqlBatchError;
var init_api = __esm(() => {
LibsqlError = class LibsqlError extends Error {
code;
extendedCode;
rawCode;
constructor(message, code, extendedCode, rawCode, cause) {
if (code !== undefined) {
message = `${code}: ${message}`;
}
super(message, { cause });
this.code = code;
this.extendedCode = extendedCode;
this.rawCode = rawCode;
this.name = "LibsqlError";
}
};
LibsqlBatchError = class LibsqlBatchError extends LibsqlError {
statementIndex;
constructor(message, statementIndex, code, extendedCode, rawCode, cause) {
super(message, code, extendedCode, rawCode, cause);
this.statementIndex = statementIndex;
this.name = "LibsqlBatchError";
}
};
});
// node_modules/@libsql/core/lib-esm/uri.js
function parseUri(text) {
const match = URI_RE.exec(text);
if (match === null) {
throw new LibsqlError(`The URL '${text}' is not in a valid format`, "URL_INVALID");
}
const groups = match.groups;
const scheme = groups["scheme"];
const authority = groups["authority"] !== undefined ? parseAuthority(groups["authority"]) : undefined;
const path = percentDecode(groups["path"]);
const query = groups["query"] !== undefined ? parseQuery(groups["query"]) : undefined;
const fragment = groups["fragment"] !== undefined ? percentDecode(groups["fragment"]) : undefined;
return { scheme, authority, path, query, fragment };
}
function parseAuthority(text) {
const match = AUTHORITY_RE.exec(text);
if (match === null) {
throw new LibsqlError("The authority part of the URL is not in a valid format", "URL_INVALID");
}
const groups = match.groups;
const host = percentDecode(groups["host_br"] ?? groups["host"]);
const port = groups["port"] ? parseInt(groups["port"], 10) : undefined;
const userinfo = groups["username"] !== undefined ? {
username: percentDecode(groups["username"]),
password: groups["password"] !== undefined ? percentDecode(groups["password"]) : undefined
} : undefined;
return { host, port, userinfo };
}
function parseQuery(text) {
const sequences = text.split("&");
const pairs = [];
for (const sequence of sequences) {
if (sequence === "") {
continue;
}
let key;
let value;
const splitIdx = sequence.indexOf("=");
if (splitIdx < 0) {
key = sequence;
value = "";
} else {
key = sequence.substring(0, splitIdx);
value = sequence.substring(splitIdx + 1);
}
pairs.push({
key: percentDecode(key.replaceAll("+", " ")),
value: percentDecode(value.replaceAll("+", " "))
});
}
return { pairs };
}
function percentDecode(text) {
try {
return decodeURIComponent(text);
} catch (e) {
if (e instanceof URIError) {
throw new LibsqlError(`URL component has invalid percent encoding: ${e}`, "URL_INVALID", undefined, undefined, e);
}
throw e;
}
}
function encodeBaseUrl(scheme, authority, path) {
if (authority === undefined) {
throw new LibsqlError(`URL with scheme ${JSON.stringify(scheme + ":")} requires authority (the "//" part)`, "URL_INVALID");
}
const schemeText = `${scheme}:`;
const hostText = encodeHost(authority.host);
const portText = encodePort(authority.port);
const userinfoText = encodeUserinfo(authority.userinfo);
const authorityText = `//${userinfoText}${hostText}${portText}`;
let pathText = path.split("/").map(encodeURIComponent).join("/");
if (pathText !== "" && !pathText.startsWith("/")) {
pathText = "/" + pathText;
}
return new URL(`${schemeText}${authorityText}${pathText}`);
}
function encodeHost(host) {
return host.includes(":") ? `[${encodeURI(host)}]` : encodeURI(host);
}
function encodePort(port) {
return port !== undefined ? `:${port}` : "";
}
function encodeUserinfo(userinfo) {
if (userinfo === undefined) {
return "";
}
const usernameText = encodeURIComponent(userinfo.username);
const passwordText = userinfo.password !== undefined ? `:${encodeURIComponent(userinfo.password)}` : "";
return `${usernameText}${passwordText}@`;
}
var URI_RE, AUTHORITY_RE;
var init_uri = __esm(() => {
init_api();
URI_RE = (() => {
const SCHEME = "(?<scheme>[A-Za-z][A-Za-z.+-]*)";
const AUTHORITY = "(?<authority>[^/?#]*)";
const PATH = "(?<path>[^?#]*)";
const QUERY = "(?<query>[^#]*)";
const FRAGMENT = "(?<fragment>.*)";
return new RegExp(`^${SCHEME}:(//${AUTHORITY})?${PATH}(\\?${QUERY})?(#${FRAGMENT})?$`, "su");
})();
AUTHORITY_RE = (() => {
return new RegExp(`^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$`, "su");
})();
});
// node_modules/js-base64/base64.mjs
var version = "3.8.1", VERSION, _hasBuffer, _TD, _TE, b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", b64chs, b64tab, b64re, _fromCC, _U8Afrom, _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_"), _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, ""), btoaPolyfill = (bin) => {
let u32, c0, c1, c2, asc = "";
const pad = bin.length % 3;
for (let i = 0;i < bin.length; ) {
if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255)
throw new TypeError("invalid character found");
u32 = c0 << 16 | c1 << 8 | c2;
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
}, _btoa, _fromUint8Array, fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a), cb_utob = (c) => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
} else {
var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320);
return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
}
}, re_utob, utob = (u) => u.replace(re_utob, cb_utob), _encode, encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src), encodeURI2 = (src) => encode(src, true), re_btou, cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var cp = (7 & cccc.charCodeAt(0)) << 18 | (63 & cccc.charCodeAt(1)) << 12 | (63 & cccc.charCodeAt(2)) << 6 | 63 & cccc.charCodeAt(3), offset = cp - 65536;
return _fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320);
case 3:
return _fromCC((15 & cccc.charCodeAt(0)) << 12 | (63 & cccc.charCodeAt(1)) << 6 | 63 & cccc.charCodeAt(2));
default:
return _fromCC((31 & cccc.charCodeAt(0)) << 6 | 63 & cccc.charCodeAt(1));
}
}, btou = (b) => b.replace(re_btou, cb_btou), atobPolyfill = (asc) => {
asc = asc.replace(/\s+/g, "");
if (!b64re.test(asc))
throw new TypeError("malformed base64.");
asc += "==".slice(2 - (asc.length & 3));
let u24, r1, r2;
let binArray = [];
for (let i = 0;i < asc.length; ) {
u24 = b64tab[asc.charAt(i++)] << 18 | b64tab[asc.charAt(i++)] << 12 | (r1 = b64tab[asc.charAt(i++)]) << 6 | (r2 = b64tab[asc.charAt(i++)]);
if (r1 === 64) {
binArray.push(_fromCC(u24 >> 16 & 255));
} else if (r2 === 64) {
binArray.push(_fromCC(u24 >> 16 & 255, u24 >> 8 & 255));
} else {
binArray.push(_fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255));
}
}
return binArray.join("");
}, _atob, _toUint8Array, toUint8Array = (a) => _toUint8Array(_unURI(a)), _decode, _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == "-" ? "+" : "/")), decode = (src) => _decode(_unURI(src)), isValid = (src) => {
if (typeof src !== "string")
return false;
const s = src.replace(/\s+/g, "").replace(/={0,2}$/, "");
return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s);
}, _noEnum = (v) => {
return {
value: v,
enumerable: false,
writable: true,
configurable: true
};
}, extendString = function() {
const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
_add("fromBase64", function() {
return decode(this);
});
_add("toBase64", function(urlsafe) {
return encode(this, urlsafe);
});
_add("toBase64URI", function() {
return encode(this, true);
});
_add("toBase64URL", function() {
return encode(this, true);
});
_add("toUint8Array", function() {
return toUint8Array(this);
});
}, extendUint8Array = function() {
const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add("toBase64", function(urlsafe) {
return fromUint8Array(this, urlsafe);
});
_add("toBase64URI", function() {
return fromUint8Array(this, true);
});
_add("toBase64URL", function() {
return fromUint8Array(this, true);
});
}, extendBuiltins = () => {
extendString();
extendUint8Array();
}, gBase64;
var init_base64 = __esm(() => {
VERSION = version;
_hasBuffer = typeof Buffer === "function";
_TD = typeof TextDecoder === "function" ? new TextDecoder("utf-8", { ignoreBOM: true }) : undefined;
_TE = typeof TextEncoder === "function" ? new TextEncoder : undefined;
b64chs = Array.prototype.slice.call(b64ch);
b64tab = ((a) => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
_fromCC = String.fromCharCode.bind(String);
_U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
_btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => {
if (/[^\x00-\xff]/.test(bin))
throw new TypeError("invalid character found");
return Buffer.from(bin, "binary").toString("base64");
} : btoaPolyfill;
_fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
const maxargs = 4096;
let strs = [];
for (let i = 0, l = u8a.length;i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(""));
};
re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
_encode = _hasBuffer ? (s) => Buffer.from(s, "utf8").toString("base64") : _TE ? (s) => _fromUint8Array(_TE.encode(s)) : (s) => _btoa(utob(s));
re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
_atob = typeof atob === "function" ? (asc) => atob(_tidyB64(asc)) : _hasBuffer ? (asc) => Buffer.from(asc, "base64").toString("binary") : atobPolyfill;
_toUint8Array = _hasBuffer ? (a) => _U8Afrom(Buffer.from(a, "base64")) : (a) => _U8Afrom(_atob(a).split("").map((c) => c.charCodeAt(0)));
_decode = _hasBuffer ? (a) => Buffer.from(a, "base64").toString("utf8") : _TD ? (a) => _TD.decode(_toUint8Array(a)) : (a) => btou(_atob(a));
gBase64 = {
version,
VERSION,
atob: _atob,
atobPolyfill,
btoa: _btoa,
btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode,
encodeURI: encodeURI2,
encodeURL: encodeURI2,
utob,
btou,
decode,
isValid,
fromUint8Array,
toUint8Array,
extendString,
extendUint8Array,
extendBuiltins
};
});
// node_modules/@libsql/core/lib-esm/util.js
function transactionModeToBegin(mode) {
if (mode === "write") {
return "BEGIN IMMEDIATE";
} else if (mode === "read") {
return "BEGIN TRANSACTION READONLY";
} else if (mode === "deferred") {
return "BEGIN DEFERRED";
} else {
throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"');
}
}
class ResultSetImpl {
columns;
columnTypes;
rows;
rowsAffected;
lastInsertRowid;
constructor(columns, columnTypes, rows, rowsAffected, lastInsertRowid) {
this.columns = columns;
this.columnTypes = columnTypes;
this.rows = rows;
this.rowsAffected = rowsAffected;
this.lastInsertRowid = lastInsertRowid;
}
toJSON() {
return {
columns: this.columns,
columnTypes: this.columnTypes,
rows: this.rows.map(rowToJson),
rowsAffected: this.rowsAffected,
lastInsertRowid: this.lastInsertRowid !== undefined ? "" + this.lastInsertRowid : null
};
}
}
function rowToJson(row) {
return Array.prototype.map.call(row, valueToJson);
}
function valueToJson(value) {
if (typeof value === "bigint") {
return "" + value;
} else if (value instanceof ArrayBuffer) {
return gBase64.fromUint8Array(new Uint8Array(value));
} else {
return value;
}
}
var supportedUrlLink = "https://github.com/libsql/libsql-client-ts#supported-urls";
var init_util = __esm(() => {
init_base64();
});
// node_modules/@libsql/core/lib-esm/config.js
function isInMemoryConfig(config) {
return config.scheme === "file" && (config.path === ":memory:" || config.path.startsWith(":memory:?"));
}
function expandConfig(config, preferHttp) {
if (typeof config !== "object") {
throw new TypeError(`Expected client configuration as object, got ${typeof config}`);
}
let { url, authToken, tls, intMode, concurrency } = config;
concurrency = Math.max(0, concurrency || 20);
intMode ??= "number";
let connectionQueryParams = [];
if (url === inMemoryMode) {
url = "file::memory:";
}
const uri = parseUri(url);
const originalUriScheme = uri.scheme.toLowerCase();
const isInMemoryMode = originalUriScheme === "file" && uri.path === inMemoryMode && uri.authority === undefined;
let queryParamsDef;
if (isInMemoryMode) {
queryParamsDef = {
cache: {
values: ["shared", "private"],
update: (key, value) => connectionQueryParams.push(`${key}=${value}`)
}
};
} else {
queryParamsDef = {
tls: {
values: ["0", "1"],
update: (_, value) => tls = value === "1"
},
authToken: {
update: (_, value) => authToken = value
}
};
}
for (const { key, value } of uri.query?.pairs ?? []) {
if (!Object.hasOwn(queryParamsDef, key)) {
throw new LibsqlError(`Unsupported URL query parameter ${JSON.stringify(key)}`, "URL_PARAM_NOT_SUPPORTED");
}
const queryParamDef = queryParamsDef[key];
if (queryParamDef.values !== undefined && !queryParamDef.values.includes(value)) {
throw new LibsqlError(`Unknown value for the "${key}" query argument: ${JSON.stringify(value)}. Supported values are: [${queryParamDef.values.map((x) => '"' + x + '"').join(", ")}]`, "URL_INVALID");
}
if (queryParamDef.update !== undefined) {
queryParamDef?.update(key, value);
}
}
const connectionQueryParamsString = connectionQueryParams.length === 0 ? "" : `?${connectionQueryParams.join("&")}`;
const path = uri.path + connectionQueryParamsString;
let scheme;
if (originalUriScheme === "libsql") {
if (tls === false) {
if (uri.authority?.port === undefined) {
throw new LibsqlError('A "libsql:" URL with ?tls=0 must specify an explicit port', "URL_INVALID");
}
scheme = preferHttp ? "http" : "ws";
} else {
scheme = preferHttp ? "https" : "wss";
}
} else {
scheme = originalUriScheme;
}
if (scheme === "http" || scheme === "ws") {
tls ??= false;
} else {
tls ??= true;
}
if (scheme !== "http" && scheme !== "ws" && scheme !== "https" && scheme !== "wss" && scheme !== "file") {
throw new LibsqlError('The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, ' + `got ${JSON.stringify(uri.scheme + ":")}. ` + `For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (intMode !== "number" && intMode !== "bigint" && intMode !== "string") {
throw new TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(intMode)}`);
}
if (uri.fragment !== undefined) {
throw new LibsqlError(`URL fragments are not supported: ${JSON.stringify("#" + uri.fragment)}`, "URL_INVALID");
}
if (isInMemoryMode) {
return {
scheme: "file",
tls: false,
path,
intMode,
concurrency,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
timeout: config.timeout,
authToken: undefined,
encryptionKey: undefined,
remoteEncryptionKey: undefined,
authority: undefined
};
}
return {
scheme,
tls,
authority: uri.authority,
path,
authToken,
intMode,
concurrency,
encryptionKey: config.encryptionKey,
remoteEncryptionKey: config.remoteEncryptionKey,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
timeout: config.timeout
};
}
var inMemoryMode = ":memory:";
var init_config = __esm(() => {
init_api();
init_uri();
init_util();
});
// node_modules/@libsql/isomorphic-ws/web.mjs
var _WebSocket;
var init_web = __esm(() => {
if (typeof WebSocket !== "undefined") {
_WebSocket = WebSocket;
} else if (typeof global !== "undefined") {
_WebSocket = global.WebSocket;
} else if (typeof window !== "undefined") {
_WebSocket = window.WebSocket;
} else if (typeof self !== "undefined") {
_WebSocket = self.WebSocket;
}
});
// node_modules/@libsql/hrana-client/lib-esm/client.js
class Client {
constructor() {
this.intMode = "number";
}
intMode;
}
// node_modules/@libsql/hrana-client/lib-esm/errors.js
var ClientError, ProtoError, ResponseError, ClosedError, WebSocketUnsupportedError, WebSocketError, HttpServerError, ProtocolVersionError, InternalError, MisuseError;
var init_errors = __esm(() => {
ClientError = class ClientError extends Error {
constructor(message) {
super(message);
this.name = "ClientError";
}
};
ProtoError = class ProtoError extends ClientError {
constructor(message) {
super(message);
this.name = "ProtoError";
}
};
ResponseError = class ResponseError extends ClientError {
code;
proto;
constructor(message, protoError) {
super(message);
this.name = "ResponseError";
this.code = protoError.code;
this.proto = protoError;
this.stack = undefined;
}
};
ClosedError = class ClosedError extends ClientError {
constructor(message, cause) {
if (cause !== undefined) {
super(`${message}: ${cause}`);
this.cause = cause;
} else {
super(message);
}
this.name = "ClosedError";
}
};
WebSocketUnsupportedError = class WebSocketUnsupportedError extends ClientError {
constructor(message) {
super(message);
this.name = "WebSocketUnsupportedError";
}
};
WebSocketError = class WebSocketError extends ClientError {
constructor(message) {
super(message);
this.name = "WebSocketError";
}
};
HttpServerError = class HttpServerError extends ClientError {
status;
constructor(message, status) {
super(message);
this.status = status;
this.name = "HttpServerError";
}
};
ProtocolVersionError = class ProtocolVersionError extends ClientError {
constructor(message) {
super(message);
this.name = "ProtocolVersionError";
}
};
InternalError = class InternalError extends ClientError {
constructor(message) {
super(message);
this.name = "InternalError";
}
};
MisuseError = class MisuseError extends ClientError {
constructor(message) {
super(message);
this.name = "MisuseError";
}
};
});
// node_modules/@libsql/hrana-client/lib-esm/encoding/json/decode.js
function string(value) {
if (typeof value === "string") {
return value;
}
throw typeError(value, "string");
}
function stringOpt(value) {
if (value === null || value === undefined) {
return;
} else if (typeof value === "string") {
return value;
}
throw typeError(value, "string or null");
}
function number(value) {
if (typeof value === "number") {
return value;
}
throw typeError(value, "number");
}
function boolean(value) {
if (typeof value === "boolean") {
return value;
}
throw typeError(value, "boolean");
}
function array(value) {
if (Array.isArray(value)) {
return value;
}
throw typeError(value, "array");
}
function object(value) {
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
return value;
}
throw typeError(value, "object");
}
function arrayObjectsMap(value, fun) {
return array(value).map((elemValue) => fun(object(elemValue)));
}
function typeError(value, expected) {
if (value === undefined) {
return new ProtoError(`Expected ${expected}, but the property was missing`);
}
let received = typeof value;
if (value === null) {
received = "null";
} else if (Array.isArray(value)) {
received = "array";
}
return new ProtoError(`Expected ${expected}, received ${received}`);
}
function readJsonObject(value, fun) {
return fun(object(value));
}
var init_decode = __esm(() => {
init_errors();
});
// node_modules/@libsql/hrana-client/lib-esm/encoding/json/encode.js
class ObjectWriter {
#output;
#isFirst;
constructor(output) {
this.#output = output;
this.#isFirst = false;
}
begin() {
this.#output.push("{");
this.#isFirst = true;
}
end() {
this.#output.push("}");
this.#isFirst = false;
}
#key(name) {
if (this.#isFirst) {
this.#output.push('"');
this.#isFirst = false;
} else {
this.#output.push(',"');
}
this.#output.push(name);
this.#output.push('":');
}
string(name, value) {
this.#key(name);
this.#output.push(JSON.stringify(value));
}
stringRaw(name, value) {
this.#key(name);
this.#output.push('"');
this.#output.push(value);
this.#output.push('"');
}
number(name, value) {
this.#key(name);
this.#output.push("" + value);
}
boolean(name, value) {
this.#key(name);
this.#output.push(value ? "true" : "false");
}
object(name, value, valueFun) {
this.#key(name);
this.begin();
valueFun(this, value);
this.end();
}
arrayObjects(name, values, valueFun) {
this.#key(name);
this.#output.push("[");
for (let i = 0;i < values.length; ++i) {
if (i !== 0) {
this.#output.push(",");
}
this.begin();
valueFun(this, values[i]);
this.end();
}
this.#output.push("]");
}
}
function writeJsonObject(value, fun) {
const output = [];
const writer = new ObjectWriter(output);
writer.begin();
fun(writer, value);
writer.end();
return output.join("");
}
// node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/util.js
var VARINT = 0, FIXED_64 = 1, LENGTH_DELIMITED = 2, FIXED_32 = 5;
// node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/decode.js
class MessageReader {
#array;
#view;
#pos;
constructor(array2) {
this.#array = array2;
this.#view = new DataView(array2.buffer, array2.byteOffset, array2.byteLength);
this.#pos = 0;
}
varint() {
let value = 0;
for (let shift = 0;; shift += 7) {
const byte = this.#array[this.#pos++];
value |= (byte & 127) << shift;
if (!(byte & 128)) {
break;
}
}
return value;
}
varintBig() {
let value = 0n;
for (let shift = 0n;; shift += 7n) {
const byte = this.#array[this.#pos++];
value |= BigInt(byte & 127) << shift;
if (!(byte & 128)) {
break;
}
}
return value;
}
bytes(length) {
const array2 = new Uint8Array(this.#array.buffer, this.#array.byteOffset + this.#pos, length);
this.#pos += length;
return array2;
}
double() {
const value = this.#view.getFloat64(this.#pos, true);
this.#pos += 8;
return value;
}
skipVarint() {
for (;; ) {
const byte = this.#array[this.#pos++];
if (!(byte & 128)) {
break;
}
}
}
skip(count) {
this.#pos += count;
}
eof() {
return this.#pos >= this.#array.byteLength;
}
}
class FieldReader {
#reader;
#wireType;
constructor(reader) {
this.#reader = reader;
this.#wireType = -1;
}
setup(wireType) {
this.#wireType = wireType;
}
#expect(expectedWireType) {
if (this.#wireType !== expectedWireType) {
throw new ProtoError(`Expected wire type ${expectedWireType}, got ${this.#wireType}`);
}
this.#wireType = -1;
}
bytes() {
this.#expect(LENGTH_DELIMITED);
const length = this.#reader.varint();
return this.#reader.bytes(length);
}
string() {
return new TextDecoder().decode(this.bytes());
}
message(def) {
return readProtobufMessage(this.bytes(), def);
}
int32() {
this.#expect(VARINT);
return this.#reader.varint();
}
uint32() {
return this.int32();
}
bool() {
return this.int32() !== 0;
}
uint64() {
this.#expect(VARINT);
return this.#reader.varintBig();
}
sint64() {
const value = this.uint64();
return value >> 1n ^ -(value & 1n);
}
double() {
this.#expect(FIXED_64);
return this.#reader.double();
}
maybeSkip() {
if (this.#wireType < 0) {
return;
} else if (this.#wireType === VARINT) {
this.#reader.skipVarint();
} else if (this.#wireType === FIXED_64) {
this.#reader.skip(8);
} else if (this.#wireType === LENGTH_DELIMITED) {
const length = this.#reader.varint();
this.#reader.skip(length);
} else if (this.#wireType === FIXED_32) {
this.#reader.skip(4);
} else {
throw new ProtoError(`Unexpected wire type ${this.#wireType}`);
}
this.#wireType = -1;
}
}
function readProtobufMessage(data, def) {
const msgReader = new MessageReader(data);
const fieldReader = new FieldReader(msgReader);
let value = def.default();
while (!msgReader.eof()) {
const key = msgReader.varint();
const tag = key >> 3;
const wireType = key & 7;
fieldReader.setup(wireType);
const tagFun = def[tag];
if (tagFun !== undefined) {
const returnedValue = tagFun(fieldReader, value);
if (returnedValue !== undefined) {
value = returnedValue;
}
}
fieldReader.maybeSkip();
}
return value;
}
var init_decode2 = __esm(() => {
init_errors();
});
// node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/encode.js
class MessageWriter {
#buf;
#array;
#view;
#pos;
constructor() {
this.#buf = new ArrayBuffer(256);
this.#array = new Uint8Array(this.#buf);
this.#view = new DataView(this.#buf);
this.#pos = 0;
}
#ensure(extra) {
if (this.#pos + extra <= this.#buf.byteLength) {
return;
}
let newCap = this.#buf.byteLength;
while (newCap < this.#pos + extra) {
newCap *= 2;
}
const newBuf = new ArrayBuffer(newCap);
const newArray = new Uint8Array(newBuf);
const newView = new DataView(newBuf);
newArray.set(new Uint8Array(this.#buf, 0, this.#pos));
this.#buf = newBuf;
this.#array = newArray;
this.#view = newView;
}
#varint(value) {
this.#ensure(5);
value = 0 | value;
do {
let byte = value & 127;
value >>>= 7;
byte |= value ? 128 : 0;
this.#array[this.#pos++] = byte;
} while (value);
}
#varintBig(value) {
this.#ensure(10);
value = value & 0xffffffffffffffffn;
do {
let byte = Number(value & 0x7fn);
value >>= 7n;
byte |= value ? 128 : 0;
this.#array[this.#pos++] = byte;
} while (value);
}
#tag(tag, wireType) {
this.#varint(tag << 3 | wireType);
}
bytes(tag, value) {
this.#tag(tag, LENGTH_DELIMITED);
this.#varint(value.byteLength);
this.#ensure(value.byteLength);
this.#array.set(value, this.#pos);
this.#pos += value.byteLength;
}
string(tag, value) {
this.bytes(tag, new TextEncoder().encode(value));
}
message(tag, value, fun) {
const writer = new MessageWriter;
fun(writer, value);
this.bytes(tag, writer.data());
}
int32(tag, value) {
this.#tag(tag, VARINT);
this.#varint(value);
}
uint32(tag, value) {
this.int32(tag, value);
}
bool(tag, value) {
this.int32(tag, value ? 1 : 0);
}
sint64(tag, value) {
this.#tag(tag, VARINT);
this.#varintBig(value << 1n ^ value >> 63n);
}
double(tag, value) {
this.#tag(tag, FIXED_64);
this.#ensure(8);
this.#view.setFloat64(this.#pos, value, true);
this.#pos += 8;
}
data() {
return new Uint8Array(this.#buf, 0, this.#pos);
}
}
function writeProtobufMessage(value, fun) {
const w = new MessageWriter;
fun(w, value);
return w.data();
}
var init_encode = () => {};
// node_modules/@libsql/hrana-client/lib-esm/encoding/index.js
var init_encoding = __esm(() => {
init_decode();
init_decode2();
init_encode();
});
// node_modules/@libsql/hrana-client/lib-esm/id_alloc.js
class IdAlloc {
#usedIds;
#freeIds;
constructor() {
this.#usedIds = new Set;
this.#freeIds = new Set;
}
alloc() {
for (const freeId2 of this.#freeIds) {
this.#freeIds.delete(freeId2);
this.#usedIds.add(freeId2);
if (!this.#usedIds.has(this.#usedIds.size - 1)) {
this.#freeIds.add(this.#usedIds.size - 1);
}
return freeId2;
}
const freeId = this.#usedIds.size;
this.#usedIds.add(freeId);
return freeId;
}
free(id) {
if (!this.#usedIds.delete(id)) {
throw new InternalError("Freeing an id that is not allocated");
}
this.#freeIds.delete(this.#usedIds.size);
if (id < this.#usedIds.size) {
this.#freeIds.add(id);
}
}
}
var init_id_alloc = __esm(() => {
init_errors();
});
// node_modules/@libsql/hrana-client/lib-esm/util.js
function impossible(value, message) {
throw new InternalError(message);
}
var init_util2 = __esm(() => {
init_errors();
});
// node_modules/@libsql/hrana-client/lib-esm/value.js
function valueToProto(value) {
if (value === null) {
return null;
} else if (typeof value === "string") {
return value;
} else if (typeof value === "number") {
if (!Number.isFinite(value)) {
throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");
}
return value;
} else if (typeof value === "bigint") {
if (value < minInteger || value > maxInteger) {
throw new RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");
}
return value;
} else if (typeof value === "boolean") {
return value ? 1n : 0n;
} else if (value instanceof ArrayBuffer) {
return new Uint8Array(value);
} else if (value instanceof Uint8Array) {
return value;
} else if (value instanceof Date) {
return +value.valueOf();
} else if (typeof value === "object") {
return "" + value.toString();
} else {
throw new TypeError("Unsupported type of value");
}
}
function valueFromProto(value, intMode) {
if (value === null) {
return null;
} else if (typeof value === "number") {
return value;
} else if (typeof value === "string") {
return value;
} else if (typeof value === "bigint") {
if (intMode === "number") {
const num = Number(value);
if (!Number.isSafeInteger(num)) {
throw new RangeError("Received integer which is too large to be safely represented as a JavaScript number");
}
return num;
} else if (intMode === "bigint") {
return value;
} else if (intMode === "string") {
return "" + value;
} else {
throw new MisuseError("Invalid value for IntMode");
}
} else if (value instanceof Uint8Array) {
return value.slice().buffer;
} else if (value === undefined) {
throw new ProtoError("Received unrecognized type of Value");
} else {
throw impossible(value, "Impossible type of Value");
}
}
var minInteger, maxInteger = 9223372036854775807n;
var init_value = __esm(() => {
init_errors();
init_util2();
minInteger = -9223372036854775808n;
});
// node_modules/@libsql/hrana-client/lib-esm/result.js
function stmtResultFromProto(result) {
return {
affectedRowCount: result.affectedRowCount,
lastInsertRowid: result.lastInsertRowid,
columnNames: result.cols.map((col) => col.name),
columnDecltypes: result.cols.map((col) => col.decltype)
};
}
function rowsResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
const rows = result.rows.map((row) => rowFromProto(stmtResult.columnNames, row, intMode));
return { ...stmtResult, rows };
}
function rowResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
let row;
if (result.rows.length > 0) {
row = rowFromProto(stmtResult.columnNames, result.rows[0], intMode);
}
return { ...stmtResult, row };
}
function valueResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
let value;
if (result.rows.length > 0 && stmtResult.columnNames.length > 0) {
value = valueFromProto(result.rows[0][0], intMode);
}
return { ...stmtResult, value };
}
function rowFromProto(colNames, values, intMode) {
const row = {};
Object.defineProperty(row, "length", { value: values.length });
for (let i = 0;i < values.length; ++i) {
const value = valueFromProto(values[i], intMode);
Object.defineProperty(row, i, { value });
const colName = colNames[i];
if (colName !== undefined && !Object.hasOwn(row, colName)) {
Object.defineProperty(row, colName, { value, enumerable: true, configurable: true, writable: true });
}
}
return row;
}
function errorFromProto(error) {
return new ResponseError(error.message, error);
}
var init_result = __esm(() => {
init_errors();
init_value();
});
// node_modules/@libsql/hrana-client/lib-esm/sql.js
class Sql {
#owner;
#sqlId;
#closed;
constructor(owner, sqlId) {
this.#owner = owner;
this.#sqlId = sqlId;
this.#closed = undefined;
}
_getSqlId(owner) {
if (this.#owner !== owner) {
throw new MisuseError("Attempted to use SQL text opened with other object");
} else if (this.#closed !== undefined) {
throw new ClosedError("SQL text is closed", this.#closed);
}
return this.#sqlId;
}
close() {
this._setClosed(new ClientError("SQL text was manually closed"));
}
_setClosed(error) {
if (this.#closed === undefined) {
this.#closed = error;
this.#owner._closeSql(this.#sqlId);
}
}
get closed() {
return this.#closed !== undefined;
}
}
function sqlToProto(owner, sql) {
if (sql instanceof Sql) {
return { sqlId: sql._getSqlId(owner) };
} else {
return { sql: "" + sql };
}
}
var init_sql = __esm(() => {
init_errors();
});
// node_modules/@libsql/hrana-client/lib-esm/queue.js
class Queue {
#pushStack;
#shiftStack;
constructor() {
this.#pushStack = [];
this.#shiftStack = [];
}
get length() {
return this.#pushStack.length + this.#shiftStack.length;
}
push(elem) {
this.#pushStack.push(elem);
}
shift() {
if (this.#shiftStack.length === 0 && this.#pushStack.length > 0) {
this.#shiftStack = this.#pushStack.reverse();
this.#pushStack = [];
}
return this.#shiftStack.pop();
}
first() {
return this.#shiftStack.length !== 0 ? this.#shiftStack[this.#shiftStack.length - 1] : this.#pushStack[0];
}
}
// node_modules/@libsql/hrana-client/lib-esm/stmt.js
class Stmt {
sql;
_args;
_namedArgs;
constructor(sql) {
this.sql = sql;
this._args = [];
this._namedArgs = new Map;
}
bindIndexes(values) {
this._args.length = 0;
for (const value of values) {
this._args.push(valueToProto(value));
}
return this;
}
bindIndex(index, value) {
if (index !== (index | 0) || index <= 0) {
throw new RangeError("Index of a positional argument must be positive integer");
}
while (this._args.length < index) {
this._args.push(null);
}
this._args[index - 1] = valueToProto(value);
return this;
}
bindName(name, value) {
this._namedArgs.set(name, valueToProto(value));
return this;
}
unbindAll() {
this._args.length = 0;
this._namedArgs.clear();
return this;
}
}
function stmtToProto(sqlOwner, stmt, wantRows) {
let inSql;
let args = [];
let namedArgs = [];
if (stmt instanceof Stmt) {
inSql = stmt.sql;
args = stmt._args;
for (const [name, value] of stmt._namedArgs.entries()) {
namedArgs.push({ name, value });
}
} else if (Array.isArray(stmt)) {
inSql = stmt[0];
if (Array.isArray(stmt[1])) {
args = stmt[1].map((arg) => valueToProto(arg));
} else {
namedArgs = Object.entries(stmt[1]).map(([name, value]) => {
return { name, value: valueToProto(value) };
});
}
} else {
inSql = stmt;
}
const { sql, sqlId } = sqlToProto(sqlOwner, inSql);
return { sql, sqlId, args, namedArgs, wantRows };
}
var init_stmt = __esm(() => {
init_sql();
init_value();
});
// node_modules/@libsql/hrana-client/lib-esm/batch.js
class Batch {
_stream;
#useCursor;
_steps;
#executed;
constructor(stream, useCursor) {
this._stream = stream;
this.#useCursor = useCursor;
this._steps = [];
this.#executed = false;
}
step() {
return new BatchStep(this);
}
execute() {
if (this.#executed) {
throw new MisuseError("This batch has already been executed");
}
this.#executed = true;
const batch = {
steps: this._steps.map((step) => step.proto)
};
if (this.#useCursor) {
return executeCursor(this._stream, this._steps, batch);
} else {
return executeRegular(this._stream, this._steps, batch);
}
}
}
function executeRegular(stream, steps, batch) {
return stream._batch(batch).then((result) => {
for (let step = 0;step < steps.length; ++step) {
const stepResult = result.stepResults.get(step);
const stepError = result.stepErrors.get(step);
steps[step].callback(stepResult, stepError);
}
});
}
async function executeCursor(stream, steps, batch) {
const cursor = await stream._openCursor(batch);
try {
let nextStep = 0;
let beginEntry = undefined;
let rows = [];
for (;; ) {
const entry = await cursor.next();
if (entry === undefined) {
break;
}
if (entry.type === "step_begin") {
if (entry.step < nextStep || entry.step >= steps.length) {
throw new ProtoError("Server produced StepBeginEntry for unexpected step");
} else if (beginEntry !== undefined) {
throw new ProtoError("Server produced StepBeginEntry before terminating previous step");
}
for (let step = nextStep;step < entry.step; ++step) {
steps[step].callback(undefined, undefined);
}
nextStep = entry.step + 1;
beginEntry = entry;
rows = [];
} else if (entry.type === "step_end") {
if (beginEntry === undefined) {
throw new ProtoError("Server produced StepEndEntry but no step is active");
}
const stmtResult = {
cols: beginEntry.cols,
rows,
affectedRowCount: entry.affectedRowCount,
lastInsertRowid: entry.lastInsertRowid
};
steps[beginEntry.step].callback(stmtResult, undefined);
beginEntry = undefined;
rows = [];
} else if (entry.type === "step_error") {
if (beginEntry === undefined) {
if (entry.step >= steps.length) {
throw new ProtoError("Server produced StepErrorEntry for unexpected step");
}
for (let step = nextStep;step < entry.step; ++step) {
steps[step].callback(undefined, undefined);
}
} else {
if (entry.step !== beginEntry.step) {
throw new ProtoError("Server produced StepErrorEntry for unexpected step");
}
beginEntry = undefined;
rows = [];
}
steps[entry.step].callback(undefined, entry.error);
nextStep = entry.step + 1;
} else if (entry.type === "row") {
if (beginEntry === undefined) {
throw new ProtoError("Server produced RowEntry but no step is active");
}
rows.push(entry.row);
} else if (entry.type === "error") {
throw errorFromProto(entry.error);
} else if (entry.type === "none") {
throw new ProtoError("Server produced unrecognized CursorEntry");
} else {
throw impossible(entry, "Impossible CursorEntry");
}
}
if (beginEntry !== undefined) {
throw new ProtoError("Server closed Cursor before terminating active step");
}
for (let step = nextStep;step < steps.length; ++step) {
steps[step].callback(undefined, undefined);
}
} finally {
cursor.close();
}
}
class BatchStep {
_batch;
#conds;
_index;
constructor(batch) {
this._batch = batch;
this.#conds = [];
this._index = undefined;
}
condition(cond) {
this.#conds.push(cond._proto);
return this;
}
query(stmt) {
return this.#add(stmt, true, rowsResultFromProto);
}
queryRow(stmt) {
return this.#add(stmt, true, rowResultFromProto);
}
queryValue(stmt) {
return this.#add(stmt, true, valueResultFromProto);
}
run(stmt) {
return this.#add(stmt, false, stmtResultFromProto);
}
#add(inStmt, wantRows, fromProto) {
if (this._index !== undefined) {
throw new MisuseError("This BatchStep has already been added to the batch");
}
const stmt = stmtToProto(this._batch._stream._sqlOwner(), inStmt, wantRows);
let condition;
if (this.#conds.length === 0) {
condition = undefined;
} else if (this.#conds.length === 1) {
condition = this.#conds[0];
} else {
condition = { type: "and", conds: this.#conds.slice() };
}
const proto = { stmt, condition };
return new Promise((outputCallback, errorCallback) => {
const callback = (stepResult, stepError) => {
if (stepResult !== undefined && stepError !== undefined) {
errorCallback(new ProtoError("Server returned both result and error"));
} else if (stepError !== undefined) {
errorCallback(errorFromProto(stepError));
} else if (stepResult !== undefined) {
outputCallback(fromProto(stepResult, this._batch._stream.intMode));
} else {
outputCallback(undefined);
}
};
this._index = this._batch._steps.length;
this._batch._steps.push({ proto, callback });
});
}
}
class BatchCond {
_batch;
_proto;
constructor(batch, proto) {
this._batch = batch;
this._proto = proto;
}
static ok(step) {
return new BatchCond(step._batch, { type: "ok", step: stepIndex(step) });
}
static error(step) {
return new BatchCond(step._batch, { type: "error", step: stepIndex(step) });
}
static not(cond) {
return new BatchCond(cond._batch, { type: "not", cond: cond._proto });
}
static and(batch, conds) {
for (const cond of conds) {
checkCondBatch(batch, cond);
}
return new BatchCond(batch, { type: "and", conds: conds.map((e) => e._proto) });
}
static or(batch, conds) {
for (const cond of conds) {
checkCondBatch(batch, cond);
}
return new BatchCond(batch, { type: "or", conds: conds.map((e) => e._proto) });
}
static isAutocommit(batch) {
batch._stream.client()._ensureVersion(3, "BatchCond.isAutocommit()");
return new BatchCond(batch, { type: "is_autocommit" });
}
}
function stepIndex(step) {
if (step._index === undefined) {
throw new MisuseError("Cannot add a condition referencing a step that has not been added to the batch");
}
return step._index;
}
function checkCondBatch(expectedBatch, cond) {
if (cond._batch !== expectedBatch) {
throw new MisuseError("Cannot mix BatchCond objects for different Batch objects");
}
}
var init_batch = __esm(() => {
init_errors();
init_result();
init_stmt();
init_util2();
});
// node_modules/@libsql/hrana-client/lib-esm/describe.js
function describeResultFromProto(result) {
return {
paramNames: result.params.map((p) => p.name),
columns: result.cols,
isExplain: result.isExplain,
isReadonly: result.isReadonly
};
}
// node_modules/@libsql/hrana-client/lib-esm/stream.js
class Stream {
constructor(intMode) {
this.intMode = intMode;
}
query(stmt) {
return this.#execute(stmt, true, rowsResultFromProto);
}
queryRow(stmt) {
return this.#execute(stmt, true, rowResultFromProto);
}
queryValue(stmt) {
return this.#execute(stmt, true, valueResultFromProto);
}
run(stmt) {
return this.#execute(stmt, false, stmtResultFromProto);
}
#execute(inStmt, wantRows, fromProto) {
const stmt = stmtToProto(this._sqlOwner(), inStmt, wantRows);
return this._execute(stmt).then((r) => fromProto(r, this.intMode));
}
batch(useCursor = false) {
return new Batch(this, useCursor);
}
describe(inSql) {
const protoSql = sqlToProto(this._sqlOwner(), inSql);
return this._describe(protoSql).then(describeResultFromProto);
}
sequence(inSql) {
const protoSql = sqlToProto(this._sqlOwner(), inSql);
return this._sequence(protoSql);
}
intMode;
}
var init_stream = __esm(() => {
init_batch();
init_result();
init_sql();
init_stmt();
});
// node_modules/@libsql/hrana-client/lib-esm/cursor.js
class Cursor {
}
// node_modules/@libsql/hrana-client/lib-esm/ws/cursor.js
var fetchChunkSize = 1000, fetchQueueSize = 10, WsCursor;
var init_cursor = __esm(() => {
init_errors();
WsCursor = class WsCursor extends Cursor {
#client;
#stream;
#cursorId;
#entryQueue;
#fetchQueue;
#closed;
#done;
constructor(client, stream, cursorId) {
super();
this.#client = client;
this.#stream = stream;
this.#cursorId = cursorId;
this.#entryQueue = new Queue;
this.#fetchQueue = new Queue;
this.#closed = undefined;
this.#done = false;
}
async next() {
for (;; ) {
if (this.#closed !== undefined) {
throw new ClosedError("Cursor is closed", this.#closed);
}
while (!this.#done && this.#fetchQueue.length < fetchQueueSize) {
this.#fetchQueue.push(this.#fetch());
}
const entry = this.#entryQueue.shift();
if (this.#done || entry !== undefined) {
return entry;
}
await this.#fetchQueue.shift().then((response) => {
if (response === undefined) {
return;
}
for (const entry2 of response.entries) {
this.#entryQueue.push(entry2);
}
this.#done ||= response.done;
});
}
}
#fetch() {
return this.#stream._sendCursorRequest(this, {
type: "fetch_cursor",
cursorId: this.#cursorId,
maxCount: fetchChunkSize
}).then((resp) => resp, (error) => {
this._setClosed(error);
return;
});
}
_setClosed(error) {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
this.#stream._sendCursorRequest(this, {
type: "close_cursor",
cursorId: this.#cursorId
}).catch(() => {
return;
});
this.#stream._cursorClosed(this);
}
close() {
this._setClosed(new ClientError("Cursor was manually closed"));
}
get closed() {
return this.#closed !== undefined;
}
};
});
// node_modules/@libsql/hrana-client/lib-esm/ws/stream.js
var WsStream;
var init_stream2 = __esm(() => {
init_errors();
init_stream();
init_cursor();
WsStream = class WsStream extends Stream {
#client;
#streamId;
#queue;
#cursor;
#closing;
#closed;
static open(client) {
const streamId = client._streamIdAlloc.alloc();
const stream = new WsStream(client, streamId);
const responseCallback = () => {
return;
};
const errorCallback =