UNPKG

flint-orm

Version:

Type-safe SQLite ORM for JavaScript

1,529 lines (1,511 loc) 225 kB
// @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/@neon-rs/load/dist/index.js var require_dist = __commonJS((exports) => { var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); } : function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.load = exports.currentTarget = undefined; var path = __importStar(__require("path")); var fs = __importStar(__require("fs")); function currentTarget() { let os = null; switch (process.platform) { case "android": switch (process.arch) { case "arm": return "android-arm-eabi"; case "arm64": return "android-arm64"; } os = "Android"; break; case "win32": switch (process.arch) { case "x64": return "win32-x64-msvc"; case "arm64": return "win32-arm64-msvc"; case "ia32": return "win32-ia32-msvc"; } os = "Windows"; break; case "darwin": switch (process.arch) { case "x64": return "darwin-x64"; case "arm64": return "darwin-arm64"; } os = "macOS"; break; case "linux": switch (process.arch) { case "x64": case "arm64": return isGlibc() ? `linux-${process.arch}-gnu` : `linux-${process.arch}-musl`; case "arm": return "linux-arm-gnueabihf"; } os = "Linux"; break; case "freebsd": if (process.arch === "x64") { return "freebsd-x64"; } os = "FreeBSD"; break; } if (os) { throw new Error(`Neon: unsupported ${os} architecture: ${process.arch}`); } throw new Error(`Neon: unsupported system: ${process.platform}`); } exports.currentTarget = currentTarget; function isGlibc() { const report = process.report?.getReport(); if (typeof report !== "object" || !report || !("header" in report)) { return false; } const header = report.header; return typeof header === "object" && !!header && "glibcVersionRuntime" in header; } function load(dirname) { const m = path.join(dirname, "index.node"); return fs.existsSync(m) ? __require(m) : null; } exports.load = load; }); // node_modules/detect-libc/lib/process.js var require_process = __commonJS((exports, module) => { var isLinux = () => process.platform === "linux"; var report = null; var getReport = () => { if (!report) { report = isLinux() && process.report ? process.report.getReport() : {}; } return report; }; module.exports = { isLinux, getReport }; }); // node_modules/detect-libc/lib/filesystem.js var require_filesystem = __commonJS((exports, module) => { var fs = __require("fs"); var LDD_PATH = "/usr/bin/ldd"; var readFileSync = (path) => fs.readFileSync(path, "utf-8"); var readFile = (path) => new Promise((resolve, reject) => { fs.readFile(path, "utf-8", (err, data) => { if (err) { reject(err); } else { resolve(data); } }); }); module.exports = { LDD_PATH, readFileSync, readFile }; }); // node_modules/detect-libc/lib/detect-libc.js var require_detect_libc = __commonJS((exports, module) => { var childProcess = __require("child_process"); var { isLinux, getReport } = require_process(); var { LDD_PATH, readFile, readFileSync } = require_filesystem(); var cachedFamilyFilesystem; var cachedVersionFilesystem; var command = "getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true"; var commandOut = ""; var safeCommand = () => { if (!commandOut) { return new Promise((resolve) => { childProcess.exec(command, (err, out) => { commandOut = err ? " " : out; resolve(commandOut); }); }); } return commandOut; }; var safeCommandSync = () => { if (!commandOut) { try { commandOut = childProcess.execSync(command, { encoding: "utf8" }); } catch (_err) { commandOut = " "; } } return commandOut; }; var GLIBC = "glibc"; var RE_GLIBC_VERSION = /GLIBC\s(\d+\.\d+)/; var MUSL = "musl"; var GLIBC_ON_LDD = GLIBC.toUpperCase(); var MUSL_ON_LDD = MUSL.toLowerCase(); var isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-"); var familyFromReport = () => { const report = getReport(); if (report.header && report.header.glibcVersionRuntime) { return GLIBC; } if (Array.isArray(report.sharedObjects)) { if (report.sharedObjects.some(isFileMusl)) { return MUSL; } } return null; }; var familyFromCommand = (out) => { const [getconf, ldd1] = out.split(/[\r\n]+/); if (getconf && getconf.includes(GLIBC)) { return GLIBC; } if (ldd1 && ldd1.includes(MUSL)) { return MUSL; } return null; }; var getFamilyFromLddContent = (content) => { if (content.includes(MUSL_ON_LDD)) { return MUSL; } if (content.includes(GLIBC_ON_LDD)) { return GLIBC; } return null; }; var familyFromFilesystem = async () => { if (cachedFamilyFilesystem !== undefined) { return cachedFamilyFilesystem; } cachedFamilyFilesystem = null; try { const lddContent = await readFile(LDD_PATH); cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); } catch (e) {} return cachedFamilyFilesystem; }; var familyFromFilesystemSync = () => { if (cachedFamilyFilesystem !== undefined) { return cachedFamilyFilesystem; } cachedFamilyFilesystem = null; try { const lddContent = readFileSync(LDD_PATH); cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); } catch (e) {} return cachedFamilyFilesystem; }; var family = async () => { let family2 = null; if (isLinux()) { family2 = await familyFromFilesystem(); if (!family2) { family2 = familyFromReport(); } if (!family2) { const out = await safeCommand(); family2 = familyFromCommand(out); } } return family2; }; var familySync = () => { let family2 = null; if (isLinux()) { family2 = familyFromFilesystemSync(); if (!family2) { family2 = familyFromReport(); } if (!family2) { const out = safeCommandSync(); family2 = familyFromCommand(out); } } return family2; }; var isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; var isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; var versionFromFilesystem = async () => { if (cachedVersionFilesystem !== undefined) { return cachedVersionFilesystem; } cachedVersionFilesystem = null; try { const lddContent = await readFile(LDD_PATH); const versionMatch = lddContent.match(RE_GLIBC_VERSION); if (versionMatch) { cachedVersionFilesystem = versionMatch[1]; } } catch (e) {} return cachedVersionFilesystem; }; var versionFromFilesystemSync = () => { if (cachedVersionFilesystem !== undefined) { return cachedVersionFilesystem; } cachedVersionFilesystem = null; try { const lddContent = readFileSync(LDD_PATH); const versionMatch = lddContent.match(RE_GLIBC_VERSION); if (versionMatch) { cachedVersionFilesystem = versionMatch[1]; } } catch (e) {} return cachedVersionFilesystem; }; var versionFromReport = () => { const report = getReport(); if (report.header && report.header.glibcVersionRuntime) { return report.header.glibcVersionRuntime; } return null; }; var versionSuffix = (s) => s.trim().split(/\s+/)[1]; var versionFromCommand = (out) => { const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); if (getconf && getconf.includes(GLIBC)) { return versionSuffix(getconf); } if (ldd1 && ldd2 && ldd1.includes(MUSL)) { return versionSuffix(ldd2); } return null; }; var version2 = async () => { let version3 = null; if (isLinux()) { version3 = await versionFromFilesystem(); if (!version3) { version3 = versionFromReport(); } if (!version3) { const out = await safeCommand(); version3 = versionFromCommand(out); } } return version3; }; var versionSync = () => { let version3 = null; if (isLinux()) { version3 = versionFromFilesystemSync(); if (!version3) { version3 = versionFromReport(); } if (!version3) { const out = safeCommandSync(); version3 = versionFromCommand(out); } } return version3; }; module.exports = { GLIBC, MUSL, family, familySync, isNonGlibcLinux, isNonGlibcLinuxSync, version: version2, versionSync }; }); // node_modules/libsql/auth.js var require_auth = __commonJS((exports, module) => { var Authorization = { ALLOW: 0, DENY: 1 }; module.exports = Authorization; }); // node_modules/libsql/sqlite-error.js var require_sqlite_error = __commonJS((exports, module) => { var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true }; function SqliteError(message, code, rawCode) { if (new.target !== SqliteError) { return new SqliteError(message, code); } if (typeof code !== "string") { throw new TypeError("Expected second argument to be a string"); } Error.call(this, message); descriptor.value = "" + message; Object.defineProperty(this, "message", descriptor); Error.captureStackTrace(this, SqliteError); this.code = code; this.rawCode = rawCode; } Object.setPrototypeOf(SqliteError, Error); Object.setPrototypeOf(SqliteError.prototype, Error.prototype); Object.defineProperty(SqliteError.prototype, "name", descriptor); module.exports = SqliteError; }); // node_modules/libsql/index.js var require_libsql = __commonJS((exports, module) => { var __dirname = "/home/runner/work/flint-orm/flint-orm/node_modules/libsql"; var { load, currentTarget } = require_dist(); var { familySync, GLIBC, MUSL } = require_detect_libc(); function requireNative() { if (process.env.LIBSQL_JS_DEV) { return load(__dirname); } let target = currentTarget(); if (familySync() == GLIBC) { switch (target) { case "linux-x64-musl": target = "linux-x64-gnu"; break; case "linux-arm64-musl": target = "linux-arm64-gnu"; break; } } if (target === "linux-arm-gnueabihf" && familySync() == MUSL) { target = "linux-arm-musleabihf"; } return __require(`@libsql/${target}`); } var { databaseOpen, databaseOpenWithSync, databaseInTransaction, databaseInterrupt, databaseClose, databaseSyncSync, databaseSyncUntilSync, databaseExecSync, databasePrepareSync, databaseDefaultSafeIntegers, databaseAuthorizer, databaseLoadExtension, databaseMaxWriteReplicationIndex, statementRaw, statementIsReader, statementGet, statementRun, statementInterrupt, statementRowsSync, statementColumns, statementSafeIntegers, rowsNext } = requireNative(); var Authorization = require_auth(); var SqliteError = require_sqlite_error(); function convertError(err) { if (err.libsqlError) { return new SqliteError(err.message, err.code, err.rawCode); } return err; } class Database { constructor(path, opts) { const encryptionCipher = opts?.encryptionCipher ?? "aes256cbc"; if (opts && opts.syncUrl) { var authToken = ""; if (opts.syncAuth) { console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."); authToken = opts.syncAuth; } else if (opts.authToken) { authToken = opts.authToken; } const encryptionKey = opts?.encryptionKey ?? ""; const syncPeriod = opts?.syncPeriod ?? 0; const readYourWrites = opts?.readYourWrites ?? true; const offline = opts?.offline ?? false; const remoteEncryptionKey = opts?.remoteEncryptionKey ?? ""; this.db = databaseOpenWithSync(path, opts.syncUrl, authToken, encryptionCipher, encryptionKey, syncPeriod, readYourWrites, offline, remoteEncryptionKey); } else { const authToken2 = opts?.authToken ?? ""; const encryptionKey = opts?.encryptionKey ?? ""; const timeout = opts?.timeout ?? 0; const remoteEncryptionKey = opts?.remoteEncryptionKey ?? ""; this.db = databaseOpen(path, authToken2, encryptionCipher, encryptionKey, timeout, remoteEncryptionKey); } this.memory = path === ":memory:"; this.readonly = false; this.name = ""; this.open = true; const db = this.db; Object.defineProperties(this, { inTransaction: { get() { return databaseInTransaction(db); } } }); } sync() { return databaseSyncSync.call(this.db); } syncUntil(replicationIndex) { return databaseSyncUntilSync.call(this.db, replicationIndex); } prepare(sql) { try { const stmt = databasePrepareSync.call(this.db, sql); return new Statement(stmt); } catch (err) { throw convertError(err); } } transaction(fn) { if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function"); const db = this; const wrapTxn = (mode) => { return (...bindParameters) => { db.exec("BEGIN " + mode); try { const result = fn(...bindParameters); db.exec("COMMIT"); return result; } catch (err) { db.exec("ROLLBACK"); throw err; } }; }; const properties = { default: { value: wrapTxn("") }, deferred: { value: wrapTxn("DEFERRED") }, immediate: { value: wrapTxn("IMMEDIATE") }, exclusive: { value: wrapTxn("EXCLUSIVE") }, database: { value: this, enumerable: true } }; Object.defineProperties(properties.default.value, properties); Object.defineProperties(properties.deferred.value, properties); Object.defineProperties(properties.immediate.value, properties); Object.defineProperties(properties.exclusive.value, properties); return properties.default.value; } pragma(source, options) { if (options == null) options = {}; if (typeof source !== "string") throw new TypeError("Expected first argument to be a string"); if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object"); const simple = options["simple"]; const stmt = this.prepare(`PRAGMA ${source}`, this, true); return simple ? stmt.pluck().get() : stmt.all(); } backup(filename, options) { throw new Error("not implemented"); } serialize(options) { throw new Error("not implemented"); } function(name, options, fn) { if (options == null) options = {}; if (typeof options === "function") { fn = options; options = {}; } if (typeof name !== "string") throw new TypeError("Expected first argument to be a string"); if (typeof fn !== "function") throw new TypeError("Expected last argument to be a function"); if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object"); if (!name) throw new TypeError("User-defined function name cannot be an empty string"); throw new Error("not implemented"); } aggregate(name, options) { if (typeof name !== "string") throw new TypeError("Expected first argument to be a string"); if (typeof options !== "object" || options === null) throw new TypeError("Expected second argument to be an options object"); if (!name) throw new TypeError("User-defined function name cannot be an empty string"); throw new Error("not implemented"); } table(name, factory) { if (typeof name !== "string") throw new TypeError("Expected first argument to be a string"); if (!name) throw new TypeError("Virtual table module name cannot be an empty string"); throw new Error("not implemented"); } authorizer(rules) { databaseAuthorizer.call(this.db, rules); } loadExtension(...args) { databaseLoadExtension.call(this.db, ...args); } maxWriteReplicationIndex() { return databaseMaxWriteReplicationIndex.call(this.db); } exec(sql) { try { databaseExecSync.call(this.db, sql); } catch (err) { throw convertError(err); } } interrupt() { databaseInterrupt.call(this.db); } close() { databaseClose.call(this.db); this.open = false; } defaultSafeIntegers(toggle) { databaseDefaultSafeIntegers.call(this.db, toggle ?? true); return this; } unsafeMode(...args) { throw new Error("not implemented"); } } class Statement { constructor(stmt) { this.stmt = stmt; this.pluckMode = false; } raw(raw) { statementRaw.call(this.stmt, raw ?? true); return this; } pluck(pluckMode) { this.pluckMode = pluckMode ?? true; return this; } get reader() { return statementIsReader.call(this.stmt); } run(...bindParameters) { try { if (bindParameters.length == 1 && typeof bindParameters[0] === "object") { return statementRun.call(this.stmt, bindParameters[0]); } else { return statementRun.call(this.stmt, bindParameters.flat()); } } catch (err) { throw convertError(err); } } get(...bindParameters) { try { if (bindParameters.length == 1 && typeof bindParameters[0] === "object") { return statementGet.call(this.stmt, bindParameters[0]); } else { return statementGet.call(this.stmt, bindParameters.flat()); } } catch (err) { throw convertError(err); } } iterate(...bindParameters) { var rows = undefined; if (bindParameters.length == 1 && typeof bindParameters[0] === "object") { rows = statementRowsSync.call(this.stmt, bindParameters[0]); } else { rows = statementRowsSync.call(this.stmt, bindParameters.flat()); } const iter = { nextRows: Array(100), nextRowIndex: 100, next() { try { if (this.nextRowIndex === 100) { rowsNext.call(rows, this.nextRows); this.nextRowIndex = 0; } const row = this.nextRows[this.nextRowIndex]; this.nextRows[this.nextRowIndex] = undefined; if (!row) { return { done: true }; } this.nextRowIndex++; return { value: row, done: false }; } catch (err) { throw convertError(err); } }, [Symbol.iterator]() { return this; } }; return iter; } all(...bindParameters) { try { const result = []; for (const row of this.iterate(...bindParameters)) { if (this.pluckMode) { result.push(row[Object.keys(row)[0]]); } else { result.push(row); } } return result; } catch (err) { throw convertError(err); } } interrupt() { statementInterrupt.call(this.stmt); } columns() { return statementColumns.call(this.stmt); } safeIntegers(toggle) { statementSafeIntegers.call(this.stmt, toggle ?? true); return this; } } module.exports = Database; module.exports.Authorization = Authorization; module.exports.SqliteError = SqliteError; }); // node_modules/@libsql/client/lib-esm/sqlite3.js import { Buffer as Buffer2 } from "buffer"; function _createClient(config) { if (config.scheme !== "file") { throw new LibsqlError(`URL scheme ${JSON.stringify(config.scheme + ":")} is not supported by the local sqlite3 client. ` + `For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED"); } const authority = config.authority; if (authority !== undefined) { const host = authority.host.toLowerCase(); if (host !== "" && host !== "localhost") { throw new LibsqlError(`Invalid host in file URL: ${JSON.stringify(authority.host)}. ` + 'A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") ' + 'or with three slashes ("file:///absolute/path.db"). ' + `For more information, please read ${supportedUrlLink}`, "URL_INVALID"); } if (authority.port !== undefined) { throw new LibsqlError("File URL cannot have a port", "URL_INVALID"); } if (authority.userinfo !== undefined) { throw new LibsqlError("File URL cannot have username and password", "URL_INVALID"); } } let isInMemory = isInMemoryConfig(config); if (isInMemory && config.syncUrl) { throw new LibsqlError(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${config.path}`, "URL_INVALID"); } let path = config.path; if (isInMemory) { path = `${config.scheme}:${config.path}`; } const options = { authToken: config.authToken, encryptionKey: config.encryptionKey, remoteEncryptionKey: config.remoteEncryptionKey, syncUrl: config.syncUrl, syncPeriod: config.syncInterval, readYourWrites: config.readYourWrites, offline: config.offline, timeout: config.timeout }; const db = new import_libsql.default(path, options); executeStmt(db, "SELECT 1 AS checkThatTheDatabaseCanBeOpened", config.intMode); return new Sqlite3Client(path, options, db, config.intMode); } class Sqlite3Client { #path; #options; #db; #intMode; closed; protocol; constructor(path, options, db, intMode) { this.#path = path; this.#options = options; this.#db = db; this.#intMode = intMode; this.closed = false; this.protocol = "file"; } async execute(stmtOrSql, args) { let stmt; if (typeof stmtOrSql === "string") { stmt = { sql: stmtOrSql, args: args || [] }; } else { stmt = stmtOrSql; } this.#checkNotClosed(); return executeStmt(this.#getDb(), stmt, this.#intMode); } async batch(stmts, mode = "deferred") { this.#checkNotClosed(); const db = this.#getDb(); try { executeStmt(db, transactionModeToBegin(mode), this.#intMode); const resultSets = []; for (let i = 0;i < stmts.length; i++) { try { if (!db.inTransaction) { throw new LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED"); } const stmt = stmts[i]; const normalizedStmt = Array.isArray(stmt) ? { sql: stmt[0], args: stmt[1] || [] } : stmt; resultSets.push(executeStmt(db, normalizedStmt, this.#intMode)); } catch (e) { if (e instanceof LibsqlBatchError) { throw e; } if (e instanceof LibsqlError) { throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined); } throw e; } } executeStmt(db, "COMMIT", this.#intMode); return resultSets; } finally { if (db.inTransaction) { executeStmt(db, "ROLLBACK", this.#intMode); } } } async migrate(stmts) { this.#checkNotClosed(); const db = this.#getDb(); try { executeStmt(db, "PRAGMA foreign_keys=off", this.#intMode); executeStmt(db, transactionModeToBegin("deferred"), this.#intMode); const resultSets = []; for (let i = 0;i < stmts.length; i++) { try { if (!db.inTransaction) { throw new LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED"); } resultSets.push(executeStmt(db, stmts[i], this.#intMode)); } catch (e) { if (e instanceof LibsqlBatchError) { throw e; } if (e instanceof LibsqlError) { throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined); } throw e; } } executeStmt(db, "COMMIT", this.#intMode); return resultSets; } finally { if (db.inTransaction) { executeStmt(db, "ROLLBACK", this.#intMode); } executeStmt(db, "PRAGMA foreign_keys=on", this.#intMode); } } async transaction(mode = "write") { const db = this.#getDb(); executeStmt(db, transactionModeToBegin(mode), this.#intMode); this.#db = null; return new Sqlite3Transaction(db, this.#intMode); } async executeMultiple(sql) { this.#checkNotClosed(); const db = this.#getDb(); try { return executeMultiple(db, sql); } finally { if (db.inTransaction) { executeStmt(db, "ROLLBACK", this.#intMode); } } } async sync() { this.#checkNotClosed(); const rep = await this.#getDb().sync(); return { frames_synced: rep.frames_synced, frame_no: rep.frame_no }; } async reconnect() { try { if (!this.closed && this.#db !== null) { this.#db.close(); } } finally { this.#db = new import_libsql.default(this.#path, this.#options); this.closed = false; } } close() { this.closed = true; if (this.#db !== null) { this.#db.close(); this.#db = null; } } #checkNotClosed() { if (this.closed) { throw new LibsqlError("The client is closed", "CLIENT_CLOSED"); } } #getDb() { if (this.#db === null) { this.#db = new import_libsql.default(this.#path, this.#options); } return this.#db; } } class Sqlite3Transaction { #database; #intMode; constructor(database, intMode) { this.#database = database; this.#intMode = intMode; } async execute(stmtOrSql, args) { let stmt; if (typeof stmtOrSql === "string") { stmt = { sql: stmtOrSql, args: args || [] }; } else { stmt = stmtOrSql; } this.#checkNotClosed(); return executeStmt(this.#database, stmt, this.#intMode); } async batch(stmts) { const resultSets = []; for (let i = 0;i < stmts.length; i++) { try { this.#checkNotClosed(); const stmt = stmts[i]; const normalizedStmt = Array.isArray(stmt) ? { sql: stmt[0], args: stmt[1] || [] } : stmt; resultSets.push(executeStmt(this.#database, normalizedStmt, this.#intMode)); } catch (e) { if (e instanceof LibsqlBatchError) { throw e; } if (e instanceof LibsqlError) { throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined); } throw e; } } return resultSets; } async executeMultiple(sql) { this.#checkNotClosed(); return executeMultiple(this.#database, sql); } async rollback() { if (!this.#database.open) { return; } this.#checkNotClosed(); executeStmt(this.#database, "ROLLBACK", this.#intMode); } async commit() { this.#checkNotClosed(); executeStmt(this.#database, "COMMIT", this.#intMode); } close() { if (this.#database.inTransaction) { executeStmt(this.#database, "ROLLBACK", this.#intMode); } } get closed() { return !this.#database.inTransaction; } #checkNotClosed() { if (this.closed) { throw new LibsqlError("The transaction is closed", "TRANSACTION_CLOSED"); } } } function executeStmt(db, stmt, intMode) { let sql; let args; if (typeof stmt === "string") { sql = stmt; args = []; } else { sql = stmt.sql; if (Array.isArray(stmt.args)) { args = stmt.args.map((value) => valueToSql(value, intMode)); } else { args = {}; for (const name in stmt.args) { const argName = name[0] === "@" || name[0] === "$" || name[0] === ":" ? name.substring(1) : name; args[argName] = valueToSql(stmt.args[name], intMode); } } } try { const sqlStmt = db.prepare(sql); sqlStmt.safeIntegers(true); let returnsData = true; try { sqlStmt.raw(true); } catch { returnsData = false; } if (returnsData) { const columns = Array.from(sqlStmt.columns().map((col) => col.name)); const columnTypes = Array.from(sqlStmt.columns().map((col) => col.type ?? "")); const rows = sqlStmt.all(args).map((sqlRow) => { return rowFromSql(sqlRow, columns, intMode); }); const rowsAffected = 0; const lastInsertRowid = undefined; return new ResultSetImpl(columns, columnTypes, rows, rowsAffected, lastInsertRowid); } else { const info = sqlStmt.run(args); const rowsAffected = info.changes; const lastInsertRowid = BigInt(info.lastInsertRowid); return new ResultSetImpl([], [], [], rowsAffected, lastInsertRowid); } } catch (e) { throw mapSqliteError(e); } } function rowFromSql(sqlRow, columns, intMode) { const row = {}; Object.defineProperty(row, "length", { value: sqlRow.length }); for (let i = 0;i < sqlRow.length; ++i) { const value = valueFromSql(sqlRow[i], intMode); Object.defineProperty(row, i, { value }); const column = columns[i]; if (!Object.hasOwn(row, column)) { Object.defineProperty(row, column, { value, enumerable: true, configurable: true, writable: true }); } } return