@kapishdima/ai-ledger 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,4461 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+
21
+ // ../../node_modules/.bun/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
22
+ var require_src = __commonJS((exports, module) => {
23
+ var ESC = "\x1B";
24
+ var CSI = `${ESC}[`;
25
+ var beep = "\x07";
26
+ var cursor = {
27
+ to(x, y) {
28
+ if (!y)
29
+ return `${CSI}${x + 1}G`;
30
+ return `${CSI}${y + 1};${x + 1}H`;
31
+ },
32
+ move(x, y) {
33
+ let ret = "";
34
+ if (x < 0)
35
+ ret += `${CSI}${-x}D`;
36
+ else if (x > 0)
37
+ ret += `${CSI}${x}C`;
38
+ if (y < 0)
39
+ ret += `${CSI}${-y}A`;
40
+ else if (y > 0)
41
+ ret += `${CSI}${y}B`;
42
+ return ret;
43
+ },
44
+ up: (count = 1) => `${CSI}${count}A`,
45
+ down: (count = 1) => `${CSI}${count}B`,
46
+ forward: (count = 1) => `${CSI}${count}C`,
47
+ backward: (count = 1) => `${CSI}${count}D`,
48
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
49
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
50
+ left: `${CSI}G`,
51
+ hide: `${CSI}?25l`,
52
+ show: `${CSI}?25h`,
53
+ save: `${ESC}7`,
54
+ restore: `${ESC}8`
55
+ };
56
+ var scroll = {
57
+ up: (count = 1) => `${CSI}S`.repeat(count),
58
+ down: (count = 1) => `${CSI}T`.repeat(count)
59
+ };
60
+ var erase = {
61
+ screen: `${CSI}2J`,
62
+ up: (count = 1) => `${CSI}1J`.repeat(count),
63
+ down: (count = 1) => `${CSI}J`.repeat(count),
64
+ line: `${CSI}2K`,
65
+ lineEnd: `${CSI}K`,
66
+ lineStart: `${CSI}1K`,
67
+ lines(count) {
68
+ let clear = "";
69
+ for (let i = 0;i < count; i++)
70
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
71
+ if (count)
72
+ clear += cursor.left;
73
+ return clear;
74
+ }
75
+ };
76
+ module.exports = { cursor, scroll, erase, beep };
77
+ });
78
+
79
+ // ../../node_modules/.bun/picocolors@1.1.1/node_modules/picocolors/picocolors.js
80
+ var require_picocolors = __commonJS((exports, module) => {
81
+ var p = process || {};
82
+ var argv = p.argv || [];
83
+ var env = p.env || {};
84
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
85
+ var formatter = (open, close, replace = open) => (input) => {
86
+ let string = "" + input, index = string.indexOf(close, open.length);
87
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
88
+ };
89
+ var replaceClose = (string, close, replace, index) => {
90
+ let result = "", cursor = 0;
91
+ do {
92
+ result += string.substring(cursor, index) + replace;
93
+ cursor = index + close.length;
94
+ index = string.indexOf(close, cursor);
95
+ } while (~index);
96
+ return result + string.substring(cursor);
97
+ };
98
+ var createColors = (enabled = isColorSupported) => {
99
+ let f = enabled ? formatter : () => String;
100
+ return {
101
+ isColorSupported: enabled,
102
+ reset: f("\x1B[0m", "\x1B[0m"),
103
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
104
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
105
+ italic: f("\x1B[3m", "\x1B[23m"),
106
+ underline: f("\x1B[4m", "\x1B[24m"),
107
+ inverse: f("\x1B[7m", "\x1B[27m"),
108
+ hidden: f("\x1B[8m", "\x1B[28m"),
109
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
110
+ black: f("\x1B[30m", "\x1B[39m"),
111
+ red: f("\x1B[31m", "\x1B[39m"),
112
+ green: f("\x1B[32m", "\x1B[39m"),
113
+ yellow: f("\x1B[33m", "\x1B[39m"),
114
+ blue: f("\x1B[34m", "\x1B[39m"),
115
+ magenta: f("\x1B[35m", "\x1B[39m"),
116
+ cyan: f("\x1B[36m", "\x1B[39m"),
117
+ white: f("\x1B[37m", "\x1B[39m"),
118
+ gray: f("\x1B[90m", "\x1B[39m"),
119
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
120
+ bgRed: f("\x1B[41m", "\x1B[49m"),
121
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
122
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
123
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
124
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
125
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
126
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
127
+ blackBright: f("\x1B[90m", "\x1B[39m"),
128
+ redBright: f("\x1B[91m", "\x1B[39m"),
129
+ greenBright: f("\x1B[92m", "\x1B[39m"),
130
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
131
+ blueBright: f("\x1B[94m", "\x1B[39m"),
132
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
133
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
134
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
135
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
136
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
137
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
138
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
139
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
140
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
141
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
142
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
143
+ };
144
+ };
145
+ module.exports = createColors();
146
+ module.exports.createColors = createColors;
147
+ });
148
+
149
+ // cli.ts
150
+ import fs2 from "fs";
151
+ import path2 from "path";
152
+ import os2 from "os";
153
+
154
+ // ../../node_modules/.bun/@clack+core@0.4.1/node_modules/@clack/core/dist/index.mjs
155
+ var import_sisteransi = __toESM(require_src(), 1);
156
+ import { stdin as $, stdout as j } from "process";
157
+ import * as f from "readline";
158
+ function J({ onlyFirst: t = false } = {}) {
159
+ const F = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
160
+ return new RegExp(F, t ? undefined : "g");
161
+ }
162
+ var Q = J();
163
+ function O(t) {
164
+ return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
165
+ }
166
+ var P = { exports: {} };
167
+ (function(t) {
168
+ var u = {};
169
+ t.exports = u, u.eastAsianWidth = function(e) {
170
+ var s = e.charCodeAt(0), i = e.length == 2 ? e.charCodeAt(1) : 0, D = s;
171
+ return 55296 <= s && s <= 56319 && 56320 <= i && i <= 57343 && (s &= 1023, i &= 1023, D = s << 10 | i, D += 65536), D == 12288 || 65281 <= D && D <= 65376 || 65504 <= D && D <= 65510 ? "F" : D == 8361 || 65377 <= D && D <= 65470 || 65474 <= D && D <= 65479 || 65482 <= D && D <= 65487 || 65490 <= D && D <= 65495 || 65498 <= D && D <= 65500 || 65512 <= D && D <= 65518 ? "H" : 4352 <= D && D <= 4447 || 4515 <= D && D <= 4519 || 4602 <= D && D <= 4607 || 9001 <= D && D <= 9002 || 11904 <= D && D <= 11929 || 11931 <= D && D <= 12019 || 12032 <= D && D <= 12245 || 12272 <= D && D <= 12283 || 12289 <= D && D <= 12350 || 12353 <= D && D <= 12438 || 12441 <= D && D <= 12543 || 12549 <= D && D <= 12589 || 12593 <= D && D <= 12686 || 12688 <= D && D <= 12730 || 12736 <= D && D <= 12771 || 12784 <= D && D <= 12830 || 12832 <= D && D <= 12871 || 12880 <= D && D <= 13054 || 13056 <= D && D <= 19903 || 19968 <= D && D <= 42124 || 42128 <= D && D <= 42182 || 43360 <= D && D <= 43388 || 44032 <= D && D <= 55203 || 55216 <= D && D <= 55238 || 55243 <= D && D <= 55291 || 63744 <= D && D <= 64255 || 65040 <= D && D <= 65049 || 65072 <= D && D <= 65106 || 65108 <= D && D <= 65126 || 65128 <= D && D <= 65131 || 110592 <= D && D <= 110593 || 127488 <= D && D <= 127490 || 127504 <= D && D <= 127546 || 127552 <= D && D <= 127560 || 127568 <= D && D <= 127569 || 131072 <= D && D <= 194367 || 177984 <= D && D <= 196605 || 196608 <= D && D <= 262141 ? "W" : 32 <= D && D <= 126 || 162 <= D && D <= 163 || 165 <= D && D <= 166 || D == 172 || D == 175 || 10214 <= D && D <= 10221 || 10629 <= D && D <= 10630 ? "Na" : D == 161 || D == 164 || 167 <= D && D <= 168 || D == 170 || 173 <= D && D <= 174 || 176 <= D && D <= 180 || 182 <= D && D <= 186 || 188 <= D && D <= 191 || D == 198 || D == 208 || 215 <= D && D <= 216 || 222 <= D && D <= 225 || D == 230 || 232 <= D && D <= 234 || 236 <= D && D <= 237 || D == 240 || 242 <= D && D <= 243 || 247 <= D && D <= 250 || D == 252 || D == 254 || D == 257 || D == 273 || D == 275 || D == 283 || 294 <= D && D <= 295 || D == 299 || 305 <= D && D <= 307 || D == 312 || 319 <= D && D <= 322 || D == 324 || 328 <= D && D <= 331 || D == 333 || 338 <= D && D <= 339 || 358 <= D && D <= 359 || D == 363 || D == 462 || D == 464 || D == 466 || D == 468 || D == 470 || D == 472 || D == 474 || D == 476 || D == 593 || D == 609 || D == 708 || D == 711 || 713 <= D && D <= 715 || D == 717 || D == 720 || 728 <= D && D <= 731 || D == 733 || D == 735 || 768 <= D && D <= 879 || 913 <= D && D <= 929 || 931 <= D && D <= 937 || 945 <= D && D <= 961 || 963 <= D && D <= 969 || D == 1025 || 1040 <= D && D <= 1103 || D == 1105 || D == 8208 || 8211 <= D && D <= 8214 || 8216 <= D && D <= 8217 || 8220 <= D && D <= 8221 || 8224 <= D && D <= 8226 || 8228 <= D && D <= 8231 || D == 8240 || 8242 <= D && D <= 8243 || D == 8245 || D == 8251 || D == 8254 || D == 8308 || D == 8319 || 8321 <= D && D <= 8324 || D == 8364 || D == 8451 || D == 8453 || D == 8457 || D == 8467 || D == 8470 || 8481 <= D && D <= 8482 || D == 8486 || D == 8491 || 8531 <= D && D <= 8532 || 8539 <= D && D <= 8542 || 8544 <= D && D <= 8555 || 8560 <= D && D <= 8569 || D == 8585 || 8592 <= D && D <= 8601 || 8632 <= D && D <= 8633 || D == 8658 || D == 8660 || D == 8679 || D == 8704 || 8706 <= D && D <= 8707 || 8711 <= D && D <= 8712 || D == 8715 || D == 8719 || D == 8721 || D == 8725 || D == 8730 || 8733 <= D && D <= 8736 || D == 8739 || D == 8741 || 8743 <= D && D <= 8748 || D == 8750 || 8756 <= D && D <= 8759 || 8764 <= D && D <= 8765 || D == 8776 || D == 8780 || D == 8786 || 8800 <= D && D <= 8801 || 8804 <= D && D <= 8807 || 8810 <= D && D <= 8811 || 8814 <= D && D <= 8815 || 8834 <= D && D <= 8835 || 8838 <= D && D <= 8839 || D == 8853 || D == 8857 || D == 8869 || D == 8895 || D == 8978 || 9312 <= D && D <= 9449 || 9451 <= D && D <= 9547 || 9552 <= D && D <= 9587 || 9600 <= D && D <= 9615 || 9618 <= D && D <= 9621 || 9632 <= D && D <= 9633 || 9635 <= D && D <= 9641 || 9650 <= D && D <= 9651 || 9654 <= D && D <= 9655 || 9660 <= D && D <= 9661 || 9664 <= D && D <= 9665 || 9670 <= D && D <= 9672 || D == 9675 || 9678 <= D && D <= 9681 || 9698 <= D && D <= 9701 || D == 9711 || 9733 <= D && D <= 9734 || D == 9737 || 9742 <= D && D <= 9743 || 9748 <= D && D <= 9749 || D == 9756 || D == 9758 || D == 9792 || D == 9794 || 9824 <= D && D <= 9825 || 9827 <= D && D <= 9829 || 9831 <= D && D <= 9834 || 9836 <= D && D <= 9837 || D == 9839 || 9886 <= D && D <= 9887 || 9918 <= D && D <= 9919 || 9924 <= D && D <= 9933 || 9935 <= D && D <= 9953 || D == 9955 || 9960 <= D && D <= 9983 || D == 10045 || D == 10071 || 10102 <= D && D <= 10111 || 11093 <= D && D <= 11097 || 12872 <= D && D <= 12879 || 57344 <= D && D <= 63743 || 65024 <= D && D <= 65039 || D == 65533 || 127232 <= D && D <= 127242 || 127248 <= D && D <= 127277 || 127280 <= D && D <= 127337 || 127344 <= D && D <= 127386 || 917760 <= D && D <= 917999 || 983040 <= D && D <= 1048573 || 1048576 <= D && D <= 1114109 ? "A" : "N";
172
+ }, u.characterLength = function(e) {
173
+ var s = this.eastAsianWidth(e);
174
+ return s == "F" || s == "W" || s == "A" ? 2 : 1;
175
+ };
176
+ function F(e) {
177
+ return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
178
+ }
179
+ u.length = function(e) {
180
+ for (var s = F(e), i = 0, D = 0;D < s.length; D++)
181
+ i = i + this.characterLength(s[D]);
182
+ return i;
183
+ }, u.slice = function(e, s, i) {
184
+ textLen = u.length(e), s = s || 0, i = i || 1, s < 0 && (s = textLen + s), i < 0 && (i = textLen + i);
185
+ for (var D = "", C = 0, o = F(e), E = 0;E < o.length; E++) {
186
+ var a = o[E], n = u.length(a);
187
+ if (C >= s - (n == 2 ? 1 : 0))
188
+ if (C + n <= i)
189
+ D += a;
190
+ else
191
+ break;
192
+ C += n;
193
+ }
194
+ return D;
195
+ };
196
+ })(P);
197
+ var X = P.exports;
198
+ var DD = O(X);
199
+ var uD = function() {
200
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
201
+ };
202
+ var FD = O(uD);
203
+ var m = 10;
204
+ var L = (t = 0) => (u) => `\x1B[${u + t}m`;
205
+ var N = (t = 0) => (u) => `\x1B[${38 + t};5;${u}m`;
206
+ var I = (t = 0) => (u, F, e) => `\x1B[${38 + t};2;${u};${F};${e}m`;
207
+ var r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
208
+ Object.keys(r.modifier);
209
+ var tD = Object.keys(r.color);
210
+ var eD = Object.keys(r.bgColor);
211
+ [...tD, ...eD];
212
+ function sD() {
213
+ const t = new Map;
214
+ for (const [u, F] of Object.entries(r)) {
215
+ for (const [e, s] of Object.entries(F))
216
+ r[e] = { open: `\x1B[${s[0]}m`, close: `\x1B[${s[1]}m` }, F[e] = r[e], t.set(s[0], s[1]);
217
+ Object.defineProperty(r, u, { value: F, enumerable: false });
218
+ }
219
+ return Object.defineProperty(r, "codes", { value: t, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = L(), r.color.ansi256 = N(), r.color.ansi16m = I(), r.bgColor.ansi = L(m), r.bgColor.ansi256 = N(m), r.bgColor.ansi16m = I(m), Object.defineProperties(r, { rgbToAnsi256: { value: (u, F, e) => u === F && F === e ? u < 8 ? 16 : u > 248 ? 231 : Math.round((u - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u / 255 * 5) + 6 * Math.round(F / 255 * 5) + Math.round(e / 255 * 5), enumerable: false }, hexToRgb: { value: (u) => {
220
+ const F = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));
221
+ if (!F)
222
+ return [0, 0, 0];
223
+ let [e] = F;
224
+ e.length === 3 && (e = [...e].map((i) => i + i).join(""));
225
+ const s = Number.parseInt(e, 16);
226
+ return [s >> 16 & 255, s >> 8 & 255, s & 255];
227
+ }, enumerable: false }, hexToAnsi256: { value: (u) => r.rgbToAnsi256(...r.hexToRgb(u)), enumerable: false }, ansi256ToAnsi: { value: (u) => {
228
+ if (u < 8)
229
+ return 30 + u;
230
+ if (u < 16)
231
+ return 90 + (u - 8);
232
+ let F, e, s;
233
+ if (u >= 232)
234
+ F = ((u - 232) * 10 + 8) / 255, e = F, s = F;
235
+ else {
236
+ u -= 16;
237
+ const C = u % 36;
238
+ F = Math.floor(u / 36) / 5, e = Math.floor(C / 6) / 5, s = C % 6 / 5;
239
+ }
240
+ const i = Math.max(F, e, s) * 2;
241
+ if (i === 0)
242
+ return 30;
243
+ let D = 30 + (Math.round(s) << 2 | Math.round(e) << 1 | Math.round(F));
244
+ return i === 2 && (D += 60), D;
245
+ }, enumerable: false }, rgbToAnsi: { value: (u, F, e) => r.ansi256ToAnsi(r.rgbToAnsi256(u, F, e)), enumerable: false }, hexToAnsi: { value: (u) => r.ansi256ToAnsi(r.hexToAnsi256(u)), enumerable: false } }), r;
246
+ }
247
+ var iD = sD();
248
+ var v = new Set(["\x1B", "\x9B"]);
249
+ var rD = "]";
250
+ var y = `${rD}8;;`;
251
+ var aD = ["up", "down", "left", "right", "space", "enter", "cancel"];
252
+ var c = { actions: new Set(aD), aliases: new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["\x03", "cancel"], ["escape", "cancel"]]) };
253
+ function k(t, u) {
254
+ if (typeof t == "string")
255
+ return c.aliases.get(t) === u;
256
+ for (const F of t)
257
+ if (F !== undefined && k(F, u))
258
+ return true;
259
+ return false;
260
+ }
261
+ var xD = globalThis.process.platform.startsWith("win");
262
+ var S = Symbol("clack:cancel");
263
+ function cD({ input: t = $, output: u = j, overwrite: F = true, hideCursor: e = true } = {}) {
264
+ const s = f.createInterface({ input: t, output: u, prompt: "", tabSize: 1 });
265
+ f.emitKeypressEvents(t, s), t.isTTY && t.setRawMode(true);
266
+ const i = (D, { name: C, sequence: o }) => {
267
+ const E = String(D);
268
+ if (k([E, C, o], "cancel")) {
269
+ e && u.write(import_sisteransi.cursor.show), process.exit(0);
270
+ return;
271
+ }
272
+ if (!F)
273
+ return;
274
+ const a = C === "return" ? 0 : -1, n = C === "return" ? -1 : 0;
275
+ f.moveCursor(u, a, n, () => {
276
+ f.clearLine(u, 1, () => {
277
+ t.once("keypress", i);
278
+ });
279
+ });
280
+ };
281
+ return e && u.write(import_sisteransi.cursor.hide), t.once("keypress", i), () => {
282
+ t.off("keypress", i), e && u.write(import_sisteransi.cursor.show), t.isTTY && !xD && t.setRawMode(false), s.terminal = false, s.close();
283
+ };
284
+ }
285
+
286
+ // ../../node_modules/.bun/@clack+prompts@0.9.1/node_modules/@clack/prompts/dist/index.mjs
287
+ var import_picocolors = __toESM(require_picocolors(), 1);
288
+ var import_sisteransi2 = __toESM(require_src(), 1);
289
+ import p from "process";
290
+ function X2() {
291
+ return p.platform !== "win32" ? p.env.TERM !== "linux" : !!p.env.CI || !!p.env.WT_SESSION || !!p.env.TERMINUS_SUBLIME || p.env.ConEmuTask === "{cmd::Cmder}" || p.env.TERM_PROGRAM === "Terminus-Sublime" || p.env.TERM_PROGRAM === "vscode" || p.env.TERM === "xterm-256color" || p.env.TERM === "alacritty" || p.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
292
+ }
293
+ var E = X2();
294
+ var u = (s, n) => E ? s : n;
295
+ var ee = u("\u25C6", "*");
296
+ var A = u("\u25A0", "x");
297
+ var B = u("\u25B2", "x");
298
+ var S2 = u("\u25C7", "o");
299
+ var te = u("\u250C", "T");
300
+ var a = u("\u2502", "|");
301
+ var m2 = u("\u2514", "\u2014");
302
+ var j2 = u("\u25CF", ">");
303
+ var R = u("\u25CB", " ");
304
+ var V = u("\u25FB", "[\u2022]");
305
+ var M = u("\u25FC", "[+]");
306
+ var G = u("\u25FB", "[ ]");
307
+ var se = u("\u25AA", "\u2022");
308
+ var N2 = u("\u2500", "-");
309
+ var re = u("\u256E", "+");
310
+ var ie = u("\u251C", "+");
311
+ var ne = u("\u256F", "+");
312
+ var ae = u("\u25CF", "\u2022");
313
+ var oe = u("\u25C6", "*");
314
+ var ce = u("\u25B2", "!");
315
+ var le = u("\u25A0", "x");
316
+ var we = (s = "") => {
317
+ process.stdout.write(`${import_picocolors.default.gray(te)} ${s}
318
+ `);
319
+ };
320
+ var fe = (s = "") => {
321
+ process.stdout.write(`${import_picocolors.default.gray(a)}
322
+ ${import_picocolors.default.gray(m2)} ${s}
323
+
324
+ `);
325
+ };
326
+ var v2 = { message: (s = "", { symbol: n = import_picocolors.default.gray(a) } = {}) => {
327
+ const t = [`${import_picocolors.default.gray(a)}`];
328
+ if (s) {
329
+ const [i, ...r2] = s.split(`
330
+ `);
331
+ t.push(`${n} ${i}`, ...r2.map((c2) => `${import_picocolors.default.gray(a)} ${c2}`));
332
+ }
333
+ process.stdout.write(`${t.join(`
334
+ `)}
335
+ `);
336
+ }, info: (s) => {
337
+ v2.message(s, { symbol: import_picocolors.default.blue(ae) });
338
+ }, success: (s) => {
339
+ v2.message(s, { symbol: import_picocolors.default.green(oe) });
340
+ }, step: (s) => {
341
+ v2.message(s, { symbol: import_picocolors.default.green(S2) });
342
+ }, warn: (s) => {
343
+ v2.message(s, { symbol: import_picocolors.default.yellow(ce) });
344
+ }, warning: (s) => {
345
+ v2.warn(s);
346
+ }, error: (s) => {
347
+ v2.message(s, { symbol: import_picocolors.default.red(le) });
348
+ } };
349
+ var L2 = () => {
350
+ const s = E ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"], n = E ? 80 : 120, t = process.env.CI === "true";
351
+ let i, r2, c2 = false, o = "", l2;
352
+ const $2 = (h) => {
353
+ const g = h > 1 ? "Something went wrong" : "Canceled";
354
+ c2 && P2(g, h);
355
+ }, d = () => $2(2), w = () => $2(1), b2 = () => {
356
+ process.on("uncaughtExceptionMonitor", d), process.on("unhandledRejection", d), process.on("SIGINT", w), process.on("SIGTERM", w), process.on("exit", $2);
357
+ }, C = () => {
358
+ process.removeListener("uncaughtExceptionMonitor", d), process.removeListener("unhandledRejection", d), process.removeListener("SIGINT", w), process.removeListener("SIGTERM", w), process.removeListener("exit", $2);
359
+ }, I2 = () => {
360
+ if (l2 === undefined)
361
+ return;
362
+ t && process.stdout.write(`
363
+ `);
364
+ const h = l2.split(`
365
+ `);
366
+ process.stdout.write(import_sisteransi2.cursor.move(-999, h.length - 1)), process.stdout.write(import_sisteransi2.erase.down(h.length));
367
+ }, x = (h) => h.replace(/\.+$/, ""), O2 = (h = "") => {
368
+ c2 = true, i = cD(), o = x(h), process.stdout.write(`${import_picocolors.default.gray(a)}
369
+ `);
370
+ let g = 0, f2 = 0;
371
+ b2(), r2 = setInterval(() => {
372
+ if (t && o === l2)
373
+ return;
374
+ I2(), l2 = o;
375
+ const W = import_picocolors.default.magenta(s[g]), _ = t ? "..." : ".".repeat(Math.floor(f2)).slice(0, 3);
376
+ process.stdout.write(`${W} ${o}${_}`), g = g + 1 < s.length ? g + 1 : 0, f2 = f2 < s.length ? f2 + 0.125 : 0;
377
+ }, n);
378
+ }, P2 = (h = "", g = 0) => {
379
+ c2 = false, clearInterval(r2), I2();
380
+ const f2 = g === 0 ? import_picocolors.default.green(S2) : g === 1 ? import_picocolors.default.red(A) : import_picocolors.default.red(B);
381
+ o = x(h ?? o), process.stdout.write(`${f2} ${o}
382
+ `), C(), i();
383
+ };
384
+ return { start: O2, stop: P2, message: (h = "") => {
385
+ o = x(h ?? o);
386
+ } };
387
+ };
388
+
389
+ // lib/db.ts
390
+ import { Database as Database2 } from "bun:sqlite";
391
+
392
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/bun-sqlite/driver.js
393
+ import { Database } from "bun:sqlite";
394
+
395
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/entity.js
396
+ var entityKind = Symbol.for("drizzle:entityKind");
397
+ var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
398
+ function is(value, type) {
399
+ if (!value || typeof value !== "object") {
400
+ return false;
401
+ }
402
+ if (value instanceof type) {
403
+ return true;
404
+ }
405
+ if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
406
+ throw new Error(`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);
407
+ }
408
+ let cls = Object.getPrototypeOf(value).constructor;
409
+ if (cls) {
410
+ while (cls) {
411
+ if (entityKind in cls && cls[entityKind] === type[entityKind]) {
412
+ return true;
413
+ }
414
+ cls = Object.getPrototypeOf(cls);
415
+ }
416
+ }
417
+ return false;
418
+ }
419
+
420
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/logger.js
421
+ class ConsoleLogWriter {
422
+ static [entityKind] = "ConsoleLogWriter";
423
+ write(message) {
424
+ console.log(message);
425
+ }
426
+ }
427
+
428
+ class DefaultLogger {
429
+ static [entityKind] = "DefaultLogger";
430
+ writer;
431
+ constructor(config) {
432
+ this.writer = config?.writer ?? new ConsoleLogWriter;
433
+ }
434
+ logQuery(query, params) {
435
+ const stringifiedParams = params.map((p2) => {
436
+ try {
437
+ return JSON.stringify(p2);
438
+ } catch {
439
+ return String(p2);
440
+ }
441
+ });
442
+ const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
443
+ this.writer.write(`Query: ${query}${paramsStr}`);
444
+ }
445
+ }
446
+
447
+ class NoopLogger {
448
+ static [entityKind] = "NoopLogger";
449
+ logQuery() {}
450
+ }
451
+
452
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/table.utils.js
453
+ var TableName = Symbol.for("drizzle:Name");
454
+
455
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/table.js
456
+ var Schema = Symbol.for("drizzle:Schema");
457
+ var Columns = Symbol.for("drizzle:Columns");
458
+ var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
459
+ var OriginalName = Symbol.for("drizzle:OriginalName");
460
+ var BaseName = Symbol.for("drizzle:BaseName");
461
+ var IsAlias = Symbol.for("drizzle:IsAlias");
462
+ var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
463
+ var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
464
+
465
+ class Table {
466
+ static [entityKind] = "Table";
467
+ static Symbol = {
468
+ Name: TableName,
469
+ Schema,
470
+ OriginalName,
471
+ Columns,
472
+ ExtraConfigColumns,
473
+ BaseName,
474
+ IsAlias,
475
+ ExtraConfigBuilder
476
+ };
477
+ [TableName];
478
+ [OriginalName];
479
+ [Schema];
480
+ [Columns];
481
+ [ExtraConfigColumns];
482
+ [BaseName];
483
+ [IsAlias] = false;
484
+ [IsDrizzleTable] = true;
485
+ [ExtraConfigBuilder] = undefined;
486
+ constructor(name, schema, baseName) {
487
+ this[TableName] = this[OriginalName] = name;
488
+ this[Schema] = schema;
489
+ this[BaseName] = baseName;
490
+ }
491
+ }
492
+ function getTableName(table) {
493
+ return table[TableName];
494
+ }
495
+ function getTableUniqueName(table) {
496
+ return `${table[Schema] ?? "public"}.${table[TableName]}`;
497
+ }
498
+
499
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/column.js
500
+ class Column {
501
+ constructor(table, config) {
502
+ this.table = table;
503
+ this.config = config;
504
+ this.name = config.name;
505
+ this.keyAsName = config.keyAsName;
506
+ this.notNull = config.notNull;
507
+ this.default = config.default;
508
+ this.defaultFn = config.defaultFn;
509
+ this.onUpdateFn = config.onUpdateFn;
510
+ this.hasDefault = config.hasDefault;
511
+ this.primary = config.primaryKey;
512
+ this.isUnique = config.isUnique;
513
+ this.uniqueName = config.uniqueName;
514
+ this.uniqueType = config.uniqueType;
515
+ this.dataType = config.dataType;
516
+ this.columnType = config.columnType;
517
+ this.generated = config.generated;
518
+ this.generatedIdentity = config.generatedIdentity;
519
+ }
520
+ static [entityKind] = "Column";
521
+ name;
522
+ keyAsName;
523
+ primary;
524
+ notNull;
525
+ default;
526
+ defaultFn;
527
+ onUpdateFn;
528
+ hasDefault;
529
+ isUnique;
530
+ uniqueName;
531
+ uniqueType;
532
+ dataType;
533
+ columnType;
534
+ enumValues = undefined;
535
+ generated = undefined;
536
+ generatedIdentity = undefined;
537
+ config;
538
+ mapFromDriverValue(value) {
539
+ return value;
540
+ }
541
+ mapToDriverValue(value) {
542
+ return value;
543
+ }
544
+ shouldDisableInsert() {
545
+ return this.config.generated !== undefined && this.config.generated.type !== "byDefault";
546
+ }
547
+ }
548
+
549
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/column-builder.js
550
+ class ColumnBuilder {
551
+ static [entityKind] = "ColumnBuilder";
552
+ config;
553
+ constructor(name, dataType, columnType) {
554
+ this.config = {
555
+ name,
556
+ keyAsName: name === "",
557
+ notNull: false,
558
+ default: undefined,
559
+ hasDefault: false,
560
+ primaryKey: false,
561
+ isUnique: false,
562
+ uniqueName: undefined,
563
+ uniqueType: undefined,
564
+ dataType,
565
+ columnType,
566
+ generated: undefined
567
+ };
568
+ }
569
+ $type() {
570
+ return this;
571
+ }
572
+ notNull() {
573
+ this.config.notNull = true;
574
+ return this;
575
+ }
576
+ default(value) {
577
+ this.config.default = value;
578
+ this.config.hasDefault = true;
579
+ return this;
580
+ }
581
+ $defaultFn(fn) {
582
+ this.config.defaultFn = fn;
583
+ this.config.hasDefault = true;
584
+ return this;
585
+ }
586
+ $default = this.$defaultFn;
587
+ $onUpdateFn(fn) {
588
+ this.config.onUpdateFn = fn;
589
+ this.config.hasDefault = true;
590
+ return this;
591
+ }
592
+ $onUpdate = this.$onUpdateFn;
593
+ primaryKey() {
594
+ this.config.primaryKey = true;
595
+ this.config.notNull = true;
596
+ return this;
597
+ }
598
+ setName(name) {
599
+ if (this.config.name !== "")
600
+ return;
601
+ this.config.name = name;
602
+ }
603
+ }
604
+
605
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/tracing-utils.js
606
+ function iife(fn, ...args) {
607
+ return fn(...args);
608
+ }
609
+
610
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/pg-core/unique-constraint.js
611
+ function uniqueKeyName(table, columns) {
612
+ return `${table[TableName]}_${columns.join("_")}_unique`;
613
+ }
614
+
615
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/pg-core/columns/common.js
616
+ class PgColumn extends Column {
617
+ constructor(table, config) {
618
+ if (!config.uniqueName) {
619
+ config.uniqueName = uniqueKeyName(table, [config.name]);
620
+ }
621
+ super(table, config);
622
+ this.table = table;
623
+ }
624
+ static [entityKind] = "PgColumn";
625
+ }
626
+
627
+ class ExtraConfigColumn extends PgColumn {
628
+ static [entityKind] = "ExtraConfigColumn";
629
+ getSQLType() {
630
+ return this.getSQLType();
631
+ }
632
+ indexConfig = {
633
+ order: this.config.order ?? "asc",
634
+ nulls: this.config.nulls ?? "last",
635
+ opClass: this.config.opClass
636
+ };
637
+ defaultConfig = {
638
+ order: "asc",
639
+ nulls: "last",
640
+ opClass: undefined
641
+ };
642
+ asc() {
643
+ this.indexConfig.order = "asc";
644
+ return this;
645
+ }
646
+ desc() {
647
+ this.indexConfig.order = "desc";
648
+ return this;
649
+ }
650
+ nullsFirst() {
651
+ this.indexConfig.nulls = "first";
652
+ return this;
653
+ }
654
+ nullsLast() {
655
+ this.indexConfig.nulls = "last";
656
+ return this;
657
+ }
658
+ op(opClass) {
659
+ this.indexConfig.opClass = opClass;
660
+ return this;
661
+ }
662
+ }
663
+
664
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/pg-core/columns/enum.js
665
+ var isPgEnumSym = Symbol.for("drizzle:isPgEnum");
666
+ function isPgEnum(obj) {
667
+ return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
668
+ }
669
+ class PgEnumColumn extends PgColumn {
670
+ static [entityKind] = "PgEnumColumn";
671
+ enum = this.config.enum;
672
+ enumValues = this.config.enum.enumValues;
673
+ constructor(table, config) {
674
+ super(table, config);
675
+ this.enum = config.enum;
676
+ }
677
+ getSQLType() {
678
+ return this.enum.enumName;
679
+ }
680
+ }
681
+
682
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/subquery.js
683
+ class Subquery {
684
+ static [entityKind] = "Subquery";
685
+ constructor(sql, selection, alias, isWith = false) {
686
+ this._ = {
687
+ brand: "Subquery",
688
+ sql,
689
+ selectedFields: selection,
690
+ alias,
691
+ isWith
692
+ };
693
+ }
694
+ }
695
+
696
+ class WithSubquery extends Subquery {
697
+ static [entityKind] = "WithSubquery";
698
+ }
699
+
700
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/version.js
701
+ var version = "0.38.4";
702
+
703
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/tracing.js
704
+ var otel;
705
+ var rawTracer;
706
+ var tracer = {
707
+ startActiveSpan(name, fn) {
708
+ if (!otel) {
709
+ return fn();
710
+ }
711
+ if (!rawTracer) {
712
+ rawTracer = otel.trace.getTracer("drizzle-orm", version);
713
+ }
714
+ return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => {
715
+ try {
716
+ return fn(span);
717
+ } catch (e2) {
718
+ span.setStatus({
719
+ code: otel2.SpanStatusCode.ERROR,
720
+ message: e2 instanceof Error ? e2.message : "Unknown error"
721
+ });
722
+ throw e2;
723
+ } finally {
724
+ span.end();
725
+ }
726
+ }), otel, rawTracer);
727
+ }
728
+ };
729
+
730
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/view-common.js
731
+ var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
732
+
733
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sql/sql.js
734
+ function isSQLWrapper(value) {
735
+ return value !== null && value !== undefined && typeof value.getSQL === "function";
736
+ }
737
+ function mergeQueries(queries) {
738
+ const result = { sql: "", params: [] };
739
+ for (const query of queries) {
740
+ result.sql += query.sql;
741
+ result.params.push(...query.params);
742
+ if (query.typings?.length) {
743
+ if (!result.typings) {
744
+ result.typings = [];
745
+ }
746
+ result.typings.push(...query.typings);
747
+ }
748
+ }
749
+ return result;
750
+ }
751
+
752
+ class StringChunk {
753
+ static [entityKind] = "StringChunk";
754
+ value;
755
+ constructor(value) {
756
+ this.value = Array.isArray(value) ? value : [value];
757
+ }
758
+ getSQL() {
759
+ return new SQL([this]);
760
+ }
761
+ }
762
+
763
+ class SQL {
764
+ constructor(queryChunks) {
765
+ this.queryChunks = queryChunks;
766
+ }
767
+ static [entityKind] = "SQL";
768
+ decoder = noopDecoder;
769
+ shouldInlineParams = false;
770
+ append(query) {
771
+ this.queryChunks.push(...query.queryChunks);
772
+ return this;
773
+ }
774
+ toQuery(config) {
775
+ return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
776
+ const query = this.buildQueryFromSourceParams(this.queryChunks, config);
777
+ span?.setAttributes({
778
+ "drizzle.query.text": query.sql,
779
+ "drizzle.query.params": JSON.stringify(query.params)
780
+ });
781
+ return query;
782
+ });
783
+ }
784
+ buildQueryFromSourceParams(chunks, _config) {
785
+ const config = Object.assign({}, _config, {
786
+ inlineParams: _config.inlineParams || this.shouldInlineParams,
787
+ paramStartIndex: _config.paramStartIndex || { value: 0 }
788
+ });
789
+ const {
790
+ casing,
791
+ escapeName,
792
+ escapeParam,
793
+ prepareTyping,
794
+ inlineParams,
795
+ paramStartIndex
796
+ } = config;
797
+ return mergeQueries(chunks.map((chunk) => {
798
+ if (is(chunk, StringChunk)) {
799
+ return { sql: chunk.value.join(""), params: [] };
800
+ }
801
+ if (is(chunk, Name)) {
802
+ return { sql: escapeName(chunk.value), params: [] };
803
+ }
804
+ if (chunk === undefined) {
805
+ return { sql: "", params: [] };
806
+ }
807
+ if (Array.isArray(chunk)) {
808
+ const result = [new StringChunk("(")];
809
+ for (const [i, p2] of chunk.entries()) {
810
+ result.push(p2);
811
+ if (i < chunk.length - 1) {
812
+ result.push(new StringChunk(", "));
813
+ }
814
+ }
815
+ result.push(new StringChunk(")"));
816
+ return this.buildQueryFromSourceParams(result, config);
817
+ }
818
+ if (is(chunk, SQL)) {
819
+ return this.buildQueryFromSourceParams(chunk.queryChunks, {
820
+ ...config,
821
+ inlineParams: inlineParams || chunk.shouldInlineParams
822
+ });
823
+ }
824
+ if (is(chunk, Table)) {
825
+ const schemaName = chunk[Table.Symbol.Schema];
826
+ const tableName = chunk[Table.Symbol.Name];
827
+ return {
828
+ sql: schemaName === undefined ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
829
+ params: []
830
+ };
831
+ }
832
+ if (is(chunk, Column)) {
833
+ const columnName = casing.getColumnCasing(chunk);
834
+ if (_config.invokeSource === "indexes") {
835
+ return { sql: escapeName(columnName), params: [] };
836
+ }
837
+ const schemaName = chunk.table[Table.Symbol.Schema];
838
+ return {
839
+ sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName),
840
+ params: []
841
+ };
842
+ }
843
+ if (is(chunk, View)) {
844
+ const schemaName = chunk[ViewBaseConfig].schema;
845
+ const viewName = chunk[ViewBaseConfig].name;
846
+ return {
847
+ sql: schemaName === undefined ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
848
+ params: []
849
+ };
850
+ }
851
+ if (is(chunk, Param)) {
852
+ if (is(chunk.value, Placeholder)) {
853
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
854
+ }
855
+ const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
856
+ if (is(mappedValue, SQL)) {
857
+ return this.buildQueryFromSourceParams([mappedValue], config);
858
+ }
859
+ if (inlineParams) {
860
+ return { sql: this.mapInlineParam(mappedValue, config), params: [] };
861
+ }
862
+ let typings = ["none"];
863
+ if (prepareTyping) {
864
+ typings = [prepareTyping(chunk.encoder)];
865
+ }
866
+ return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
867
+ }
868
+ if (is(chunk, Placeholder)) {
869
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
870
+ }
871
+ if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {
872
+ return { sql: escapeName(chunk.fieldAlias), params: [] };
873
+ }
874
+ if (is(chunk, Subquery)) {
875
+ if (chunk._.isWith) {
876
+ return { sql: escapeName(chunk._.alias), params: [] };
877
+ }
878
+ return this.buildQueryFromSourceParams([
879
+ new StringChunk("("),
880
+ chunk._.sql,
881
+ new StringChunk(") "),
882
+ new Name(chunk._.alias)
883
+ ], config);
884
+ }
885
+ if (isPgEnum(chunk)) {
886
+ if (chunk.schema) {
887
+ return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
888
+ }
889
+ return { sql: escapeName(chunk.enumName), params: [] };
890
+ }
891
+ if (isSQLWrapper(chunk)) {
892
+ if (chunk.shouldOmitSQLParens?.()) {
893
+ return this.buildQueryFromSourceParams([chunk.getSQL()], config);
894
+ }
895
+ return this.buildQueryFromSourceParams([
896
+ new StringChunk("("),
897
+ chunk.getSQL(),
898
+ new StringChunk(")")
899
+ ], config);
900
+ }
901
+ if (inlineParams) {
902
+ return { sql: this.mapInlineParam(chunk, config), params: [] };
903
+ }
904
+ return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
905
+ }));
906
+ }
907
+ mapInlineParam(chunk, { escapeString }) {
908
+ if (chunk === null) {
909
+ return "null";
910
+ }
911
+ if (typeof chunk === "number" || typeof chunk === "boolean") {
912
+ return chunk.toString();
913
+ }
914
+ if (typeof chunk === "string") {
915
+ return escapeString(chunk);
916
+ }
917
+ if (typeof chunk === "object") {
918
+ const mappedValueAsString = chunk.toString();
919
+ if (mappedValueAsString === "[object Object]") {
920
+ return escapeString(JSON.stringify(chunk));
921
+ }
922
+ return escapeString(mappedValueAsString);
923
+ }
924
+ throw new Error("Unexpected param value: " + chunk);
925
+ }
926
+ getSQL() {
927
+ return this;
928
+ }
929
+ as(alias) {
930
+ if (alias === undefined) {
931
+ return this;
932
+ }
933
+ return new SQL.Aliased(this, alias);
934
+ }
935
+ mapWith(decoder) {
936
+ this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
937
+ return this;
938
+ }
939
+ inlineParams() {
940
+ this.shouldInlineParams = true;
941
+ return this;
942
+ }
943
+ if(condition) {
944
+ return condition ? this : undefined;
945
+ }
946
+ }
947
+
948
+ class Name {
949
+ constructor(value) {
950
+ this.value = value;
951
+ }
952
+ static [entityKind] = "Name";
953
+ brand;
954
+ getSQL() {
955
+ return new SQL([this]);
956
+ }
957
+ }
958
+ function isDriverValueEncoder(value) {
959
+ return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
960
+ }
961
+ var noopDecoder = {
962
+ mapFromDriverValue: (value) => value
963
+ };
964
+ var noopEncoder = {
965
+ mapToDriverValue: (value) => value
966
+ };
967
+ var noopMapper = {
968
+ ...noopDecoder,
969
+ ...noopEncoder
970
+ };
971
+
972
+ class Param {
973
+ constructor(value, encoder = noopEncoder) {
974
+ this.value = value;
975
+ this.encoder = encoder;
976
+ }
977
+ static [entityKind] = "Param";
978
+ brand;
979
+ getSQL() {
980
+ return new SQL([this]);
981
+ }
982
+ }
983
+ function sql(strings, ...params) {
984
+ const queryChunks = [];
985
+ if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
986
+ queryChunks.push(new StringChunk(strings[0]));
987
+ }
988
+ for (const [paramIndex, param2] of params.entries()) {
989
+ queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
990
+ }
991
+ return new SQL(queryChunks);
992
+ }
993
+ ((sql2) => {
994
+ function empty() {
995
+ return new SQL([]);
996
+ }
997
+ sql2.empty = empty;
998
+ function fromList(list) {
999
+ return new SQL(list);
1000
+ }
1001
+ sql2.fromList = fromList;
1002
+ function raw(str) {
1003
+ return new SQL([new StringChunk(str)]);
1004
+ }
1005
+ sql2.raw = raw;
1006
+ function join(chunks, separator) {
1007
+ const result = [];
1008
+ for (const [i, chunk] of chunks.entries()) {
1009
+ if (i > 0 && separator !== undefined) {
1010
+ result.push(separator);
1011
+ }
1012
+ result.push(chunk);
1013
+ }
1014
+ return new SQL(result);
1015
+ }
1016
+ sql2.join = join;
1017
+ function identifier(value) {
1018
+ return new Name(value);
1019
+ }
1020
+ sql2.identifier = identifier;
1021
+ function placeholder2(name2) {
1022
+ return new Placeholder(name2);
1023
+ }
1024
+ sql2.placeholder = placeholder2;
1025
+ function param2(value, encoder) {
1026
+ return new Param(value, encoder);
1027
+ }
1028
+ sql2.param = param2;
1029
+ })(sql || (sql = {}));
1030
+ ((SQL2) => {
1031
+
1032
+ class Aliased {
1033
+ constructor(sql2, fieldAlias) {
1034
+ this.sql = sql2;
1035
+ this.fieldAlias = fieldAlias;
1036
+ }
1037
+ static [entityKind] = "SQL.Aliased";
1038
+ isSelectionField = false;
1039
+ getSQL() {
1040
+ return this.sql;
1041
+ }
1042
+ clone() {
1043
+ return new Aliased(this.sql, this.fieldAlias);
1044
+ }
1045
+ }
1046
+ SQL2.Aliased = Aliased;
1047
+ })(SQL || (SQL = {}));
1048
+
1049
+ class Placeholder {
1050
+ constructor(name2) {
1051
+ this.name = name2;
1052
+ }
1053
+ static [entityKind] = "Placeholder";
1054
+ getSQL() {
1055
+ return new SQL([this]);
1056
+ }
1057
+ }
1058
+ function fillPlaceholders(params, values) {
1059
+ return params.map((p2) => {
1060
+ if (is(p2, Placeholder)) {
1061
+ if (!(p2.name in values)) {
1062
+ throw new Error(`No value for placeholder "${p2.name}" was provided`);
1063
+ }
1064
+ return values[p2.name];
1065
+ }
1066
+ if (is(p2, Param) && is(p2.value, Placeholder)) {
1067
+ if (!(p2.value.name in values)) {
1068
+ throw new Error(`No value for placeholder "${p2.value.name}" was provided`);
1069
+ }
1070
+ return p2.encoder.mapToDriverValue(values[p2.value.name]);
1071
+ }
1072
+ return p2;
1073
+ });
1074
+ }
1075
+ var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
1076
+
1077
+ class View {
1078
+ static [entityKind] = "View";
1079
+ [ViewBaseConfig];
1080
+ [IsDrizzleView] = true;
1081
+ constructor({ name: name2, schema, selectedFields, query }) {
1082
+ this[ViewBaseConfig] = {
1083
+ name: name2,
1084
+ originalName: name2,
1085
+ schema,
1086
+ selectedFields,
1087
+ query,
1088
+ isExisting: !query,
1089
+ isAlias: false
1090
+ };
1091
+ }
1092
+ getSQL() {
1093
+ return new SQL([this]);
1094
+ }
1095
+ }
1096
+ Column.prototype.getSQL = function() {
1097
+ return new SQL([this]);
1098
+ };
1099
+ Table.prototype.getSQL = function() {
1100
+ return new SQL([this]);
1101
+ };
1102
+ Subquery.prototype.getSQL = function() {
1103
+ return new SQL([this]);
1104
+ };
1105
+
1106
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/utils.js
1107
+ function mapResultRow(columns, row, joinsNotNullableMap) {
1108
+ const nullifyMap = {};
1109
+ const result = columns.reduce((result2, { path, field }, columnIndex) => {
1110
+ let decoder;
1111
+ if (is(field, Column)) {
1112
+ decoder = field;
1113
+ } else if (is(field, SQL)) {
1114
+ decoder = field.decoder;
1115
+ } else {
1116
+ decoder = field.sql.decoder;
1117
+ }
1118
+ let node = result2;
1119
+ for (const [pathChunkIndex, pathChunk] of path.entries()) {
1120
+ if (pathChunkIndex < path.length - 1) {
1121
+ if (!(pathChunk in node)) {
1122
+ node[pathChunk] = {};
1123
+ }
1124
+ node = node[pathChunk];
1125
+ } else {
1126
+ const rawValue = row[columnIndex];
1127
+ const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
1128
+ if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
1129
+ const objectName = path[0];
1130
+ if (!(objectName in nullifyMap)) {
1131
+ nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
1132
+ } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
1133
+ nullifyMap[objectName] = false;
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+ return result2;
1139
+ }, {});
1140
+ if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
1141
+ for (const [objectName, tableName] of Object.entries(nullifyMap)) {
1142
+ if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
1143
+ result[objectName] = null;
1144
+ }
1145
+ }
1146
+ }
1147
+ return result;
1148
+ }
1149
+ function orderSelectedFields(fields, pathPrefix) {
1150
+ return Object.entries(fields).reduce((result, [name, field]) => {
1151
+ if (typeof name !== "string") {
1152
+ return result;
1153
+ }
1154
+ const newPath = pathPrefix ? [...pathPrefix, name] : [name];
1155
+ if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
1156
+ result.push({ path: newPath, field });
1157
+ } else if (is(field, Table)) {
1158
+ result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
1159
+ } else {
1160
+ result.push(...orderSelectedFields(field, newPath));
1161
+ }
1162
+ return result;
1163
+ }, []);
1164
+ }
1165
+ function haveSameKeys(left, right) {
1166
+ const leftKeys = Object.keys(left);
1167
+ const rightKeys = Object.keys(right);
1168
+ if (leftKeys.length !== rightKeys.length) {
1169
+ return false;
1170
+ }
1171
+ for (const [index, key] of leftKeys.entries()) {
1172
+ if (key !== rightKeys[index]) {
1173
+ return false;
1174
+ }
1175
+ }
1176
+ return true;
1177
+ }
1178
+ function mapUpdateSet(table, values) {
1179
+ const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => {
1180
+ if (is(value, SQL) || is(value, Column)) {
1181
+ return [key, value];
1182
+ } else {
1183
+ return [key, new Param(value, table[Table.Symbol.Columns][key])];
1184
+ }
1185
+ });
1186
+ if (entries.length === 0) {
1187
+ throw new Error("No values to set");
1188
+ }
1189
+ return Object.fromEntries(entries);
1190
+ }
1191
+ function applyMixins(baseClass, extendedClasses) {
1192
+ for (const extendedClass of extendedClasses) {
1193
+ for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
1194
+ if (name === "constructor")
1195
+ continue;
1196
+ Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null));
1197
+ }
1198
+ }
1199
+ }
1200
+ function getTableColumns(table) {
1201
+ return table[Table.Symbol.Columns];
1202
+ }
1203
+ function getTableLikeName(table) {
1204
+ return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];
1205
+ }
1206
+ function getColumnNameAndConfig(a2, b2) {
1207
+ return {
1208
+ name: typeof a2 === "string" && a2.length > 0 ? a2 : "",
1209
+ config: typeof a2 === "object" ? a2 : b2
1210
+ };
1211
+ }
1212
+ function isConfig(data) {
1213
+ if (typeof data !== "object" || data === null)
1214
+ return false;
1215
+ if (data.constructor.name !== "Object")
1216
+ return false;
1217
+ if ("logger" in data) {
1218
+ const type = typeof data["logger"];
1219
+ if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined")
1220
+ return false;
1221
+ return true;
1222
+ }
1223
+ if ("schema" in data) {
1224
+ const type = typeof data["logger"];
1225
+ if (type !== "object" && type !== "undefined")
1226
+ return false;
1227
+ return true;
1228
+ }
1229
+ if ("casing" in data) {
1230
+ const type = typeof data["logger"];
1231
+ if (type !== "string" && type !== "undefined")
1232
+ return false;
1233
+ return true;
1234
+ }
1235
+ if ("mode" in data) {
1236
+ if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined)
1237
+ return false;
1238
+ return true;
1239
+ }
1240
+ if ("connection" in data) {
1241
+ const type = typeof data["connection"];
1242
+ if (type !== "string" && type !== "object" && type !== "undefined")
1243
+ return false;
1244
+ return true;
1245
+ }
1246
+ if ("client" in data) {
1247
+ const type = typeof data["client"];
1248
+ if (type !== "object" && type !== "function" && type !== "undefined")
1249
+ return false;
1250
+ return true;
1251
+ }
1252
+ if (Object.keys(data).length === 0)
1253
+ return true;
1254
+ return false;
1255
+ }
1256
+
1257
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/pg-core/table.js
1258
+ var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
1259
+ var EnableRLS = Symbol.for("drizzle:EnableRLS");
1260
+
1261
+ class PgTable extends Table {
1262
+ static [entityKind] = "PgTable";
1263
+ static Symbol = Object.assign({}, Table.Symbol, {
1264
+ InlineForeignKeys,
1265
+ EnableRLS
1266
+ });
1267
+ [InlineForeignKeys] = [];
1268
+ [EnableRLS] = false;
1269
+ [Table.Symbol.ExtraConfigBuilder] = undefined;
1270
+ }
1271
+
1272
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/pg-core/primary-keys.js
1273
+ class PrimaryKeyBuilder {
1274
+ static [entityKind] = "PgPrimaryKeyBuilder";
1275
+ columns;
1276
+ name;
1277
+ constructor(columns, name) {
1278
+ this.columns = columns;
1279
+ this.name = name;
1280
+ }
1281
+ build(table) {
1282
+ return new PrimaryKey(table, this.columns, this.name);
1283
+ }
1284
+ }
1285
+
1286
+ class PrimaryKey {
1287
+ constructor(table, columns, name) {
1288
+ this.table = table;
1289
+ this.columns = columns;
1290
+ this.name = name;
1291
+ }
1292
+ static [entityKind] = "PgPrimaryKey";
1293
+ columns;
1294
+ name;
1295
+ getName() {
1296
+ return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`;
1297
+ }
1298
+ }
1299
+
1300
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sql/expressions/conditions.js
1301
+ function bindIfParam(value, column) {
1302
+ if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) {
1303
+ return new Param(value, column);
1304
+ }
1305
+ return value;
1306
+ }
1307
+ var eq = (left, right) => {
1308
+ return sql`${left} = ${bindIfParam(right, left)}`;
1309
+ };
1310
+ var ne2 = (left, right) => {
1311
+ return sql`${left} <> ${bindIfParam(right, left)}`;
1312
+ };
1313
+ function and(...unfilteredConditions) {
1314
+ const conditions = unfilteredConditions.filter((c2) => c2 !== undefined);
1315
+ if (conditions.length === 0) {
1316
+ return;
1317
+ }
1318
+ if (conditions.length === 1) {
1319
+ return new SQL(conditions);
1320
+ }
1321
+ return new SQL([
1322
+ new StringChunk("("),
1323
+ sql.join(conditions, new StringChunk(" and ")),
1324
+ new StringChunk(")")
1325
+ ]);
1326
+ }
1327
+ function or(...unfilteredConditions) {
1328
+ const conditions = unfilteredConditions.filter((c2) => c2 !== undefined);
1329
+ if (conditions.length === 0) {
1330
+ return;
1331
+ }
1332
+ if (conditions.length === 1) {
1333
+ return new SQL(conditions);
1334
+ }
1335
+ return new SQL([
1336
+ new StringChunk("("),
1337
+ sql.join(conditions, new StringChunk(" or ")),
1338
+ new StringChunk(")")
1339
+ ]);
1340
+ }
1341
+ function not(condition) {
1342
+ return sql`not ${condition}`;
1343
+ }
1344
+ var gt = (left, right) => {
1345
+ return sql`${left} > ${bindIfParam(right, left)}`;
1346
+ };
1347
+ var gte = (left, right) => {
1348
+ return sql`${left} >= ${bindIfParam(right, left)}`;
1349
+ };
1350
+ var lt = (left, right) => {
1351
+ return sql`${left} < ${bindIfParam(right, left)}`;
1352
+ };
1353
+ var lte = (left, right) => {
1354
+ return sql`${left} <= ${bindIfParam(right, left)}`;
1355
+ };
1356
+ function inArray(column, values) {
1357
+ if (Array.isArray(values)) {
1358
+ if (values.length === 0) {
1359
+ return sql`false`;
1360
+ }
1361
+ return sql`${column} in ${values.map((v3) => bindIfParam(v3, column))}`;
1362
+ }
1363
+ return sql`${column} in ${bindIfParam(values, column)}`;
1364
+ }
1365
+ function notInArray(column, values) {
1366
+ if (Array.isArray(values)) {
1367
+ if (values.length === 0) {
1368
+ return sql`true`;
1369
+ }
1370
+ return sql`${column} not in ${values.map((v3) => bindIfParam(v3, column))}`;
1371
+ }
1372
+ return sql`${column} not in ${bindIfParam(values, column)}`;
1373
+ }
1374
+ function isNull(value) {
1375
+ return sql`${value} is null`;
1376
+ }
1377
+ function isNotNull(value) {
1378
+ return sql`${value} is not null`;
1379
+ }
1380
+ function exists(subquery) {
1381
+ return sql`exists ${subquery}`;
1382
+ }
1383
+ function notExists(subquery) {
1384
+ return sql`not exists ${subquery}`;
1385
+ }
1386
+ function between(column, min, max) {
1387
+ return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1388
+ }
1389
+ function notBetween(column, min, max) {
1390
+ return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;
1391
+ }
1392
+ function like(column, value) {
1393
+ return sql`${column} like ${value}`;
1394
+ }
1395
+ function notLike(column, value) {
1396
+ return sql`${column} not like ${value}`;
1397
+ }
1398
+ function ilike(column, value) {
1399
+ return sql`${column} ilike ${value}`;
1400
+ }
1401
+ function notIlike(column, value) {
1402
+ return sql`${column} not ilike ${value}`;
1403
+ }
1404
+
1405
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sql/expressions/select.js
1406
+ function asc(column) {
1407
+ return sql`${column} asc`;
1408
+ }
1409
+ function desc(column) {
1410
+ return sql`${column} desc`;
1411
+ }
1412
+
1413
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/relations.js
1414
+ class Relation {
1415
+ constructor(sourceTable, referencedTable, relationName) {
1416
+ this.sourceTable = sourceTable;
1417
+ this.referencedTable = referencedTable;
1418
+ this.relationName = relationName;
1419
+ this.referencedTableName = referencedTable[Table.Symbol.Name];
1420
+ }
1421
+ static [entityKind] = "Relation";
1422
+ referencedTableName;
1423
+ fieldName;
1424
+ }
1425
+
1426
+ class Relations {
1427
+ constructor(table, config) {
1428
+ this.table = table;
1429
+ this.config = config;
1430
+ }
1431
+ static [entityKind] = "Relations";
1432
+ }
1433
+
1434
+ class One extends Relation {
1435
+ constructor(sourceTable, referencedTable, config, isNullable) {
1436
+ super(sourceTable, referencedTable, config?.relationName);
1437
+ this.config = config;
1438
+ this.isNullable = isNullable;
1439
+ }
1440
+ static [entityKind] = "One";
1441
+ withFieldName(fieldName) {
1442
+ const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable);
1443
+ relation.fieldName = fieldName;
1444
+ return relation;
1445
+ }
1446
+ }
1447
+
1448
+ class Many extends Relation {
1449
+ constructor(sourceTable, referencedTable, config) {
1450
+ super(sourceTable, referencedTable, config?.relationName);
1451
+ this.config = config;
1452
+ }
1453
+ static [entityKind] = "Many";
1454
+ withFieldName(fieldName) {
1455
+ const relation = new Many(this.sourceTable, this.referencedTable, this.config);
1456
+ relation.fieldName = fieldName;
1457
+ return relation;
1458
+ }
1459
+ }
1460
+ function getOperators() {
1461
+ return {
1462
+ and,
1463
+ between,
1464
+ eq,
1465
+ exists,
1466
+ gt,
1467
+ gte,
1468
+ ilike,
1469
+ inArray,
1470
+ isNull,
1471
+ isNotNull,
1472
+ like,
1473
+ lt,
1474
+ lte,
1475
+ ne: ne2,
1476
+ not,
1477
+ notBetween,
1478
+ notExists,
1479
+ notLike,
1480
+ notIlike,
1481
+ notInArray,
1482
+ or,
1483
+ sql
1484
+ };
1485
+ }
1486
+ function getOrderByOperators() {
1487
+ return {
1488
+ sql,
1489
+ asc,
1490
+ desc
1491
+ };
1492
+ }
1493
+ function extractTablesRelationalConfig(schema, configHelpers) {
1494
+ if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) {
1495
+ schema = schema["default"];
1496
+ }
1497
+ const tableNamesMap = {};
1498
+ const relationsBuffer = {};
1499
+ const tablesConfig = {};
1500
+ for (const [key, value] of Object.entries(schema)) {
1501
+ if (is(value, Table)) {
1502
+ const dbName = getTableUniqueName(value);
1503
+ const bufferedRelations = relationsBuffer[dbName];
1504
+ tableNamesMap[dbName] = key;
1505
+ tablesConfig[key] = {
1506
+ tsName: key,
1507
+ dbName: value[Table.Symbol.Name],
1508
+ schema: value[Table.Symbol.Schema],
1509
+ columns: value[Table.Symbol.Columns],
1510
+ relations: bufferedRelations?.relations ?? {},
1511
+ primaryKey: bufferedRelations?.primaryKey ?? []
1512
+ };
1513
+ for (const column of Object.values(value[Table.Symbol.Columns])) {
1514
+ if (column.primary) {
1515
+ tablesConfig[key].primaryKey.push(column);
1516
+ }
1517
+ }
1518
+ const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]);
1519
+ if (extraConfig) {
1520
+ for (const configEntry of Object.values(extraConfig)) {
1521
+ if (is(configEntry, PrimaryKeyBuilder)) {
1522
+ tablesConfig[key].primaryKey.push(...configEntry.columns);
1523
+ }
1524
+ }
1525
+ }
1526
+ } else if (is(value, Relations)) {
1527
+ const dbName = getTableUniqueName(value.table);
1528
+ const tableName = tableNamesMap[dbName];
1529
+ const relations2 = value.config(configHelpers(value.table));
1530
+ let primaryKey;
1531
+ for (const [relationName, relation] of Object.entries(relations2)) {
1532
+ if (tableName) {
1533
+ const tableConfig = tablesConfig[tableName];
1534
+ tableConfig.relations[relationName] = relation;
1535
+ if (primaryKey) {
1536
+ tableConfig.primaryKey.push(...primaryKey);
1537
+ }
1538
+ } else {
1539
+ if (!(dbName in relationsBuffer)) {
1540
+ relationsBuffer[dbName] = {
1541
+ relations: {},
1542
+ primaryKey
1543
+ };
1544
+ }
1545
+ relationsBuffer[dbName].relations[relationName] = relation;
1546
+ }
1547
+ }
1548
+ }
1549
+ }
1550
+ return { tables: tablesConfig, tableNamesMap };
1551
+ }
1552
+ function createOne(sourceTable) {
1553
+ return function one(table, config) {
1554
+ return new One(sourceTable, table, config, config?.fields.reduce((res, f2) => res && f2.notNull, true) ?? false);
1555
+ };
1556
+ }
1557
+ function createMany(sourceTable) {
1558
+ return function many(referencedTable, config) {
1559
+ return new Many(sourceTable, referencedTable, config);
1560
+ };
1561
+ }
1562
+ function normalizeRelation(schema, tableNamesMap, relation) {
1563
+ if (is(relation, One) && relation.config) {
1564
+ return {
1565
+ fields: relation.config.fields,
1566
+ references: relation.config.references
1567
+ };
1568
+ }
1569
+ const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
1570
+ if (!referencedTableTsName) {
1571
+ throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`);
1572
+ }
1573
+ const referencedTableConfig = schema[referencedTableTsName];
1574
+ if (!referencedTableConfig) {
1575
+ throw new Error(`Table "${referencedTableTsName}" not found in schema`);
1576
+ }
1577
+ const sourceTable = relation.sourceTable;
1578
+ const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
1579
+ if (!sourceTableTsName) {
1580
+ throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`);
1581
+ }
1582
+ const reverseRelations = [];
1583
+ for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) {
1584
+ if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
1585
+ reverseRelations.push(referencedTableRelation);
1586
+ }
1587
+ }
1588
+ if (reverseRelations.length > 1) {
1589
+ throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`);
1590
+ }
1591
+ if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
1592
+ return {
1593
+ fields: reverseRelations[0].config.references,
1594
+ references: reverseRelations[0].config.fields
1595
+ };
1596
+ }
1597
+ throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`);
1598
+ }
1599
+ function createTableRelationsHelpers(sourceTable) {
1600
+ return {
1601
+ one: createOne(sourceTable),
1602
+ many: createMany(sourceTable)
1603
+ };
1604
+ }
1605
+ function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
1606
+ const result = {};
1607
+ for (const [
1608
+ selectionItemIndex,
1609
+ selectionItem
1610
+ ] of buildQueryResultSelection.entries()) {
1611
+ if (selectionItem.isJson) {
1612
+ const relation = tableConfig.relations[selectionItem.tsKey];
1613
+ const rawSubRows = row[selectionItemIndex];
1614
+ const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
1615
+ result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue));
1616
+ } else {
1617
+ const value = mapColumnValue(row[selectionItemIndex]);
1618
+ const field = selectionItem.field;
1619
+ let decoder;
1620
+ if (is(field, Column)) {
1621
+ decoder = field;
1622
+ } else if (is(field, SQL)) {
1623
+ decoder = field.decoder;
1624
+ } else {
1625
+ decoder = field.sql.decoder;
1626
+ }
1627
+ result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
1628
+ }
1629
+ }
1630
+ return result;
1631
+ }
1632
+
1633
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/alias.js
1634
+ class ColumnAliasProxyHandler {
1635
+ constructor(table) {
1636
+ this.table = table;
1637
+ }
1638
+ static [entityKind] = "ColumnAliasProxyHandler";
1639
+ get(columnObj, prop) {
1640
+ if (prop === "table") {
1641
+ return this.table;
1642
+ }
1643
+ return columnObj[prop];
1644
+ }
1645
+ }
1646
+
1647
+ class TableAliasProxyHandler {
1648
+ constructor(alias, replaceOriginalName) {
1649
+ this.alias = alias;
1650
+ this.replaceOriginalName = replaceOriginalName;
1651
+ }
1652
+ static [entityKind] = "TableAliasProxyHandler";
1653
+ get(target, prop) {
1654
+ if (prop === Table.Symbol.IsAlias) {
1655
+ return true;
1656
+ }
1657
+ if (prop === Table.Symbol.Name) {
1658
+ return this.alias;
1659
+ }
1660
+ if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
1661
+ return this.alias;
1662
+ }
1663
+ if (prop === ViewBaseConfig) {
1664
+ return {
1665
+ ...target[ViewBaseConfig],
1666
+ name: this.alias,
1667
+ isAlias: true
1668
+ };
1669
+ }
1670
+ if (prop === Table.Symbol.Columns) {
1671
+ const columns = target[Table.Symbol.Columns];
1672
+ if (!columns) {
1673
+ return columns;
1674
+ }
1675
+ const proxiedColumns = {};
1676
+ Object.keys(columns).map((key) => {
1677
+ proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this)));
1678
+ });
1679
+ return proxiedColumns;
1680
+ }
1681
+ const value = target[prop];
1682
+ if (is(value, Column)) {
1683
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
1684
+ }
1685
+ return value;
1686
+ }
1687
+ }
1688
+ function aliasedTable(table, tableAlias) {
1689
+ return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
1690
+ }
1691
+ function aliasedTableColumn(column, tableAlias) {
1692
+ return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))));
1693
+ }
1694
+ function mapColumnsInAliasedSQLToAlias(query, alias) {
1695
+ return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
1696
+ }
1697
+ function mapColumnsInSQLToAlias(query, alias) {
1698
+ return sql.join(query.queryChunks.map((c2) => {
1699
+ if (is(c2, Column)) {
1700
+ return aliasedTableColumn(c2, alias);
1701
+ }
1702
+ if (is(c2, SQL)) {
1703
+ return mapColumnsInSQLToAlias(c2, alias);
1704
+ }
1705
+ if (is(c2, SQL.Aliased)) {
1706
+ return mapColumnsInAliasedSQLToAlias(c2, alias);
1707
+ }
1708
+ return c2;
1709
+ }));
1710
+ }
1711
+
1712
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/selection-proxy.js
1713
+ class SelectionProxyHandler {
1714
+ static [entityKind] = "SelectionProxyHandler";
1715
+ config;
1716
+ constructor(config) {
1717
+ this.config = { ...config };
1718
+ }
1719
+ get(subquery, prop) {
1720
+ if (prop === "_") {
1721
+ return {
1722
+ ...subquery["_"],
1723
+ selectedFields: new Proxy(subquery._.selectedFields, this)
1724
+ };
1725
+ }
1726
+ if (prop === ViewBaseConfig) {
1727
+ return {
1728
+ ...subquery[ViewBaseConfig],
1729
+ selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)
1730
+ };
1731
+ }
1732
+ if (typeof prop === "symbol") {
1733
+ return subquery[prop];
1734
+ }
1735
+ const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery;
1736
+ const value = columns[prop];
1737
+ if (is(value, SQL.Aliased)) {
1738
+ if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
1739
+ return value.sql;
1740
+ }
1741
+ const newValue = value.clone();
1742
+ newValue.isSelectionField = true;
1743
+ return newValue;
1744
+ }
1745
+ if (is(value, SQL)) {
1746
+ if (this.config.sqlBehavior === "sql") {
1747
+ return value;
1748
+ }
1749
+ throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`);
1750
+ }
1751
+ if (is(value, Column)) {
1752
+ if (this.config.alias) {
1753
+ return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false))));
1754
+ }
1755
+ return value;
1756
+ }
1757
+ if (typeof value !== "object" || value === null) {
1758
+ return value;
1759
+ }
1760
+ return new Proxy(value, new SelectionProxyHandler(this.config));
1761
+ }
1762
+ }
1763
+
1764
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/query-promise.js
1765
+ class QueryPromise {
1766
+ static [entityKind] = "QueryPromise";
1767
+ [Symbol.toStringTag] = "QueryPromise";
1768
+ catch(onRejected) {
1769
+ return this.then(undefined, onRejected);
1770
+ }
1771
+ finally(onFinally) {
1772
+ return this.then((value) => {
1773
+ onFinally?.();
1774
+ return value;
1775
+ }, (reason) => {
1776
+ onFinally?.();
1777
+ throw reason;
1778
+ });
1779
+ }
1780
+ then(onFulfilled, onRejected) {
1781
+ return this.execute().then(onFulfilled, onRejected);
1782
+ }
1783
+ }
1784
+
1785
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
1786
+ class ForeignKeyBuilder {
1787
+ static [entityKind] = "SQLiteForeignKeyBuilder";
1788
+ reference;
1789
+ _onUpdate;
1790
+ _onDelete;
1791
+ constructor(config, actions) {
1792
+ this.reference = () => {
1793
+ const { name, columns, foreignColumns } = config();
1794
+ return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns };
1795
+ };
1796
+ if (actions) {
1797
+ this._onUpdate = actions.onUpdate;
1798
+ this._onDelete = actions.onDelete;
1799
+ }
1800
+ }
1801
+ onUpdate(action) {
1802
+ this._onUpdate = action;
1803
+ return this;
1804
+ }
1805
+ onDelete(action) {
1806
+ this._onDelete = action;
1807
+ return this;
1808
+ }
1809
+ build(table) {
1810
+ return new ForeignKey(table, this);
1811
+ }
1812
+ }
1813
+
1814
+ class ForeignKey {
1815
+ constructor(table, builder) {
1816
+ this.table = table;
1817
+ this.reference = builder.reference;
1818
+ this.onUpdate = builder._onUpdate;
1819
+ this.onDelete = builder._onDelete;
1820
+ }
1821
+ static [entityKind] = "SQLiteForeignKey";
1822
+ reference;
1823
+ onUpdate;
1824
+ onDelete;
1825
+ getName() {
1826
+ const { name, columns, foreignColumns } = this.reference();
1827
+ const columnNames = columns.map((column) => column.name);
1828
+ const foreignColumnNames = foreignColumns.map((column) => column.name);
1829
+ const chunks = [
1830
+ this.table[TableName],
1831
+ ...columnNames,
1832
+ foreignColumns[0].table[TableName],
1833
+ ...foreignColumnNames
1834
+ ];
1835
+ return name ?? `${chunks.join("_")}_fk`;
1836
+ }
1837
+ }
1838
+
1839
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
1840
+ function uniqueKeyName2(table, columns) {
1841
+ return `${table[TableName]}_${columns.join("_")}_unique`;
1842
+ }
1843
+
1844
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/common.js
1845
+ class SQLiteColumnBuilder extends ColumnBuilder {
1846
+ static [entityKind] = "SQLiteColumnBuilder";
1847
+ foreignKeyConfigs = [];
1848
+ references(ref, actions = {}) {
1849
+ this.foreignKeyConfigs.push({ ref, actions });
1850
+ return this;
1851
+ }
1852
+ unique(name) {
1853
+ this.config.isUnique = true;
1854
+ this.config.uniqueName = name;
1855
+ return this;
1856
+ }
1857
+ generatedAlwaysAs(as, config) {
1858
+ this.config.generated = {
1859
+ as,
1860
+ type: "always",
1861
+ mode: config?.mode ?? "virtual"
1862
+ };
1863
+ return this;
1864
+ }
1865
+ buildForeignKeys(column, table) {
1866
+ return this.foreignKeyConfigs.map(({ ref, actions }) => {
1867
+ return ((ref2, actions2) => {
1868
+ const builder = new ForeignKeyBuilder(() => {
1869
+ const foreignColumn = ref2();
1870
+ return { columns: [column], foreignColumns: [foreignColumn] };
1871
+ });
1872
+ if (actions2.onUpdate) {
1873
+ builder.onUpdate(actions2.onUpdate);
1874
+ }
1875
+ if (actions2.onDelete) {
1876
+ builder.onDelete(actions2.onDelete);
1877
+ }
1878
+ return builder.build(table);
1879
+ })(ref, actions);
1880
+ });
1881
+ }
1882
+ }
1883
+
1884
+ class SQLiteColumn extends Column {
1885
+ constructor(table, config) {
1886
+ if (!config.uniqueName) {
1887
+ config.uniqueName = uniqueKeyName2(table, [config.name]);
1888
+ }
1889
+ super(table, config);
1890
+ this.table = table;
1891
+ }
1892
+ static [entityKind] = "SQLiteColumn";
1893
+ }
1894
+
1895
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/blob.js
1896
+ class SQLiteBigIntBuilder extends SQLiteColumnBuilder {
1897
+ static [entityKind] = "SQLiteBigIntBuilder";
1898
+ constructor(name) {
1899
+ super(name, "bigint", "SQLiteBigInt");
1900
+ }
1901
+ build(table) {
1902
+ return new SQLiteBigInt(table, this.config);
1903
+ }
1904
+ }
1905
+
1906
+ class SQLiteBigInt extends SQLiteColumn {
1907
+ static [entityKind] = "SQLiteBigInt";
1908
+ getSQLType() {
1909
+ return "blob";
1910
+ }
1911
+ mapFromDriverValue(value) {
1912
+ if (Buffer.isBuffer(value)) {
1913
+ return BigInt(value.toString());
1914
+ }
1915
+ if (value instanceof ArrayBuffer) {
1916
+ const decoder = new TextDecoder;
1917
+ return BigInt(decoder.decode(value));
1918
+ }
1919
+ return BigInt(String.fromCodePoint(...value));
1920
+ }
1921
+ mapToDriverValue(value) {
1922
+ return Buffer.from(value.toString());
1923
+ }
1924
+ }
1925
+
1926
+ class SQLiteBlobJsonBuilder extends SQLiteColumnBuilder {
1927
+ static [entityKind] = "SQLiteBlobJsonBuilder";
1928
+ constructor(name) {
1929
+ super(name, "json", "SQLiteBlobJson");
1930
+ }
1931
+ build(table) {
1932
+ return new SQLiteBlobJson(table, this.config);
1933
+ }
1934
+ }
1935
+
1936
+ class SQLiteBlobJson extends SQLiteColumn {
1937
+ static [entityKind] = "SQLiteBlobJson";
1938
+ getSQLType() {
1939
+ return "blob";
1940
+ }
1941
+ mapFromDriverValue(value) {
1942
+ if (Buffer.isBuffer(value)) {
1943
+ return JSON.parse(value.toString());
1944
+ }
1945
+ if (value instanceof ArrayBuffer) {
1946
+ const decoder = new TextDecoder;
1947
+ return JSON.parse(decoder.decode(value));
1948
+ }
1949
+ return JSON.parse(String.fromCodePoint(...value));
1950
+ }
1951
+ mapToDriverValue(value) {
1952
+ return Buffer.from(JSON.stringify(value));
1953
+ }
1954
+ }
1955
+
1956
+ class SQLiteBlobBufferBuilder extends SQLiteColumnBuilder {
1957
+ static [entityKind] = "SQLiteBlobBufferBuilder";
1958
+ constructor(name) {
1959
+ super(name, "buffer", "SQLiteBlobBuffer");
1960
+ }
1961
+ build(table) {
1962
+ return new SQLiteBlobBuffer(table, this.config);
1963
+ }
1964
+ }
1965
+
1966
+ class SQLiteBlobBuffer extends SQLiteColumn {
1967
+ static [entityKind] = "SQLiteBlobBuffer";
1968
+ getSQLType() {
1969
+ return "blob";
1970
+ }
1971
+ }
1972
+ function blob(a2, b2) {
1973
+ const { name, config } = getColumnNameAndConfig(a2, b2);
1974
+ if (config?.mode === "json") {
1975
+ return new SQLiteBlobJsonBuilder(name);
1976
+ }
1977
+ if (config?.mode === "bigint") {
1978
+ return new SQLiteBigIntBuilder(name);
1979
+ }
1980
+ return new SQLiteBlobBufferBuilder(name);
1981
+ }
1982
+
1983
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/custom.js
1984
+ class SQLiteCustomColumnBuilder extends SQLiteColumnBuilder {
1985
+ static [entityKind] = "SQLiteCustomColumnBuilder";
1986
+ constructor(name, fieldConfig, customTypeParams) {
1987
+ super(name, "custom", "SQLiteCustomColumn");
1988
+ this.config.fieldConfig = fieldConfig;
1989
+ this.config.customTypeParams = customTypeParams;
1990
+ }
1991
+ build(table) {
1992
+ return new SQLiteCustomColumn(table, this.config);
1993
+ }
1994
+ }
1995
+
1996
+ class SQLiteCustomColumn extends SQLiteColumn {
1997
+ static [entityKind] = "SQLiteCustomColumn";
1998
+ sqlName;
1999
+ mapTo;
2000
+ mapFrom;
2001
+ constructor(table, config) {
2002
+ super(table, config);
2003
+ this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
2004
+ this.mapTo = config.customTypeParams.toDriver;
2005
+ this.mapFrom = config.customTypeParams.fromDriver;
2006
+ }
2007
+ getSQLType() {
2008
+ return this.sqlName;
2009
+ }
2010
+ mapFromDriverValue(value) {
2011
+ return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
2012
+ }
2013
+ mapToDriverValue(value) {
2014
+ return typeof this.mapTo === "function" ? this.mapTo(value) : value;
2015
+ }
2016
+ }
2017
+ function customType(customTypeParams) {
2018
+ return (a2, b2) => {
2019
+ const { name, config } = getColumnNameAndConfig(a2, b2);
2020
+ return new SQLiteCustomColumnBuilder(name, config, customTypeParams);
2021
+ };
2022
+ }
2023
+
2024
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/integer.js
2025
+ class SQLiteBaseIntegerBuilder extends SQLiteColumnBuilder {
2026
+ static [entityKind] = "SQLiteBaseIntegerBuilder";
2027
+ constructor(name, dataType, columnType) {
2028
+ super(name, dataType, columnType);
2029
+ this.config.autoIncrement = false;
2030
+ }
2031
+ primaryKey(config) {
2032
+ if (config?.autoIncrement) {
2033
+ this.config.autoIncrement = true;
2034
+ }
2035
+ this.config.hasDefault = true;
2036
+ return super.primaryKey();
2037
+ }
2038
+ }
2039
+
2040
+ class SQLiteBaseInteger extends SQLiteColumn {
2041
+ static [entityKind] = "SQLiteBaseInteger";
2042
+ autoIncrement = this.config.autoIncrement;
2043
+ getSQLType() {
2044
+ return "integer";
2045
+ }
2046
+ }
2047
+
2048
+ class SQLiteIntegerBuilder extends SQLiteBaseIntegerBuilder {
2049
+ static [entityKind] = "SQLiteIntegerBuilder";
2050
+ constructor(name) {
2051
+ super(name, "number", "SQLiteInteger");
2052
+ }
2053
+ build(table) {
2054
+ return new SQLiteInteger(table, this.config);
2055
+ }
2056
+ }
2057
+
2058
+ class SQLiteInteger extends SQLiteBaseInteger {
2059
+ static [entityKind] = "SQLiteInteger";
2060
+ }
2061
+
2062
+ class SQLiteTimestampBuilder extends SQLiteBaseIntegerBuilder {
2063
+ static [entityKind] = "SQLiteTimestampBuilder";
2064
+ constructor(name, mode) {
2065
+ super(name, "date", "SQLiteTimestamp");
2066
+ this.config.mode = mode;
2067
+ }
2068
+ defaultNow() {
2069
+ return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
2070
+ }
2071
+ build(table) {
2072
+ return new SQLiteTimestamp(table, this.config);
2073
+ }
2074
+ }
2075
+
2076
+ class SQLiteTimestamp extends SQLiteBaseInteger {
2077
+ static [entityKind] = "SQLiteTimestamp";
2078
+ mode = this.config.mode;
2079
+ mapFromDriverValue(value) {
2080
+ if (this.config.mode === "timestamp") {
2081
+ return new Date(value * 1000);
2082
+ }
2083
+ return new Date(value);
2084
+ }
2085
+ mapToDriverValue(value) {
2086
+ const unix = value.getTime();
2087
+ if (this.config.mode === "timestamp") {
2088
+ return Math.floor(unix / 1000);
2089
+ }
2090
+ return unix;
2091
+ }
2092
+ }
2093
+
2094
+ class SQLiteBooleanBuilder extends SQLiteBaseIntegerBuilder {
2095
+ static [entityKind] = "SQLiteBooleanBuilder";
2096
+ constructor(name, mode) {
2097
+ super(name, "boolean", "SQLiteBoolean");
2098
+ this.config.mode = mode;
2099
+ }
2100
+ build(table) {
2101
+ return new SQLiteBoolean(table, this.config);
2102
+ }
2103
+ }
2104
+
2105
+ class SQLiteBoolean extends SQLiteBaseInteger {
2106
+ static [entityKind] = "SQLiteBoolean";
2107
+ mode = this.config.mode;
2108
+ mapFromDriverValue(value) {
2109
+ return Number(value) === 1;
2110
+ }
2111
+ mapToDriverValue(value) {
2112
+ return value ? 1 : 0;
2113
+ }
2114
+ }
2115
+ function integer(a2, b2) {
2116
+ const { name, config } = getColumnNameAndConfig(a2, b2);
2117
+ if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
2118
+ return new SQLiteTimestampBuilder(name, config.mode);
2119
+ }
2120
+ if (config?.mode === "boolean") {
2121
+ return new SQLiteBooleanBuilder(name, config.mode);
2122
+ }
2123
+ return new SQLiteIntegerBuilder(name);
2124
+ }
2125
+
2126
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/numeric.js
2127
+ class SQLiteNumericBuilder extends SQLiteColumnBuilder {
2128
+ static [entityKind] = "SQLiteNumericBuilder";
2129
+ constructor(name) {
2130
+ super(name, "string", "SQLiteNumeric");
2131
+ }
2132
+ build(table) {
2133
+ return new SQLiteNumeric(table, this.config);
2134
+ }
2135
+ }
2136
+
2137
+ class SQLiteNumeric extends SQLiteColumn {
2138
+ static [entityKind] = "SQLiteNumeric";
2139
+ getSQLType() {
2140
+ return "numeric";
2141
+ }
2142
+ }
2143
+ function numeric(name) {
2144
+ return new SQLiteNumericBuilder(name ?? "");
2145
+ }
2146
+
2147
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/real.js
2148
+ class SQLiteRealBuilder extends SQLiteColumnBuilder {
2149
+ static [entityKind] = "SQLiteRealBuilder";
2150
+ constructor(name) {
2151
+ super(name, "number", "SQLiteReal");
2152
+ }
2153
+ build(table) {
2154
+ return new SQLiteReal(table, this.config);
2155
+ }
2156
+ }
2157
+
2158
+ class SQLiteReal extends SQLiteColumn {
2159
+ static [entityKind] = "SQLiteReal";
2160
+ getSQLType() {
2161
+ return "real";
2162
+ }
2163
+ }
2164
+ function real(name) {
2165
+ return new SQLiteRealBuilder(name ?? "");
2166
+ }
2167
+
2168
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/text.js
2169
+ class SQLiteTextBuilder extends SQLiteColumnBuilder {
2170
+ static [entityKind] = "SQLiteTextBuilder";
2171
+ constructor(name, config) {
2172
+ super(name, "string", "SQLiteText");
2173
+ this.config.enumValues = config.enum;
2174
+ this.config.length = config.length;
2175
+ }
2176
+ build(table) {
2177
+ return new SQLiteText(table, this.config);
2178
+ }
2179
+ }
2180
+
2181
+ class SQLiteText extends SQLiteColumn {
2182
+ static [entityKind] = "SQLiteText";
2183
+ enumValues = this.config.enumValues;
2184
+ length = this.config.length;
2185
+ constructor(table, config) {
2186
+ super(table, config);
2187
+ }
2188
+ getSQLType() {
2189
+ return `text${this.config.length ? `(${this.config.length})` : ""}`;
2190
+ }
2191
+ }
2192
+
2193
+ class SQLiteTextJsonBuilder extends SQLiteColumnBuilder {
2194
+ static [entityKind] = "SQLiteTextJsonBuilder";
2195
+ constructor(name) {
2196
+ super(name, "json", "SQLiteTextJson");
2197
+ }
2198
+ build(table) {
2199
+ return new SQLiteTextJson(table, this.config);
2200
+ }
2201
+ }
2202
+
2203
+ class SQLiteTextJson extends SQLiteColumn {
2204
+ static [entityKind] = "SQLiteTextJson";
2205
+ getSQLType() {
2206
+ return "text";
2207
+ }
2208
+ mapFromDriverValue(value) {
2209
+ return JSON.parse(value);
2210
+ }
2211
+ mapToDriverValue(value) {
2212
+ return JSON.stringify(value);
2213
+ }
2214
+ }
2215
+ function text(a2, b2 = {}) {
2216
+ const { name, config } = getColumnNameAndConfig(a2, b2);
2217
+ if (config.mode === "json") {
2218
+ return new SQLiteTextJsonBuilder(name);
2219
+ }
2220
+ return new SQLiteTextBuilder(name, config);
2221
+ }
2222
+
2223
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/columns/all.js
2224
+ function getSQLiteColumnBuilders() {
2225
+ return {
2226
+ blob,
2227
+ customType,
2228
+ integer,
2229
+ numeric,
2230
+ real,
2231
+ text
2232
+ };
2233
+ }
2234
+
2235
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/table.js
2236
+ var InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
2237
+
2238
+ class SQLiteTable extends Table {
2239
+ static [entityKind] = "SQLiteTable";
2240
+ static Symbol = Object.assign({}, Table.Symbol, {
2241
+ InlineForeignKeys: InlineForeignKeys2
2242
+ });
2243
+ [Table.Symbol.Columns];
2244
+ [InlineForeignKeys2] = [];
2245
+ [Table.Symbol.ExtraConfigBuilder] = undefined;
2246
+ }
2247
+ function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
2248
+ const rawTable = new SQLiteTable(name, schema, baseName);
2249
+ const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
2250
+ const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => {
2251
+ const colBuilder = colBuilderBase;
2252
+ colBuilder.setName(name2);
2253
+ const column = colBuilder.build(rawTable);
2254
+ rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable));
2255
+ return [name2, column];
2256
+ }));
2257
+ const table = Object.assign(rawTable, builtColumns);
2258
+ table[Table.Symbol.Columns] = builtColumns;
2259
+ table[Table.Symbol.ExtraConfigColumns] = builtColumns;
2260
+ if (extraConfig) {
2261
+ table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
2262
+ }
2263
+ return table;
2264
+ }
2265
+ var sqliteTable = (name, columns, extraConfig) => {
2266
+ return sqliteTableBase(name, columns, extraConfig);
2267
+ };
2268
+
2269
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
2270
+ class SQLiteDeleteBase extends QueryPromise {
2271
+ constructor(table, session, dialect, withList) {
2272
+ super();
2273
+ this.table = table;
2274
+ this.session = session;
2275
+ this.dialect = dialect;
2276
+ this.config = { table, withList };
2277
+ }
2278
+ static [entityKind] = "SQLiteDelete";
2279
+ config;
2280
+ where(where) {
2281
+ this.config.where = where;
2282
+ return this;
2283
+ }
2284
+ orderBy(...columns) {
2285
+ if (typeof columns[0] === "function") {
2286
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
2287
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
2288
+ this.config.orderBy = orderByArray;
2289
+ } else {
2290
+ const orderByArray = columns;
2291
+ this.config.orderBy = orderByArray;
2292
+ }
2293
+ return this;
2294
+ }
2295
+ limit(limit) {
2296
+ this.config.limit = limit;
2297
+ return this;
2298
+ }
2299
+ returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
2300
+ this.config.returning = orderSelectedFields(fields);
2301
+ return this;
2302
+ }
2303
+ getSQL() {
2304
+ return this.dialect.buildDeleteQuery(this.config);
2305
+ }
2306
+ toSQL() {
2307
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
2308
+ return rest;
2309
+ }
2310
+ _prepare(isOneTimeQuery = true) {
2311
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
2312
+ }
2313
+ prepare() {
2314
+ return this._prepare(false);
2315
+ }
2316
+ run = (placeholderValues) => {
2317
+ return this._prepare().run(placeholderValues);
2318
+ };
2319
+ all = (placeholderValues) => {
2320
+ return this._prepare().all(placeholderValues);
2321
+ };
2322
+ get = (placeholderValues) => {
2323
+ return this._prepare().get(placeholderValues);
2324
+ };
2325
+ values = (placeholderValues) => {
2326
+ return this._prepare().values(placeholderValues);
2327
+ };
2328
+ async execute(placeholderValues) {
2329
+ return this._prepare().execute(placeholderValues);
2330
+ }
2331
+ $dynamic() {
2332
+ return this;
2333
+ }
2334
+ }
2335
+
2336
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/casing.js
2337
+ function toSnakeCase(input) {
2338
+ const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
2339
+ return words.map((word) => word.toLowerCase()).join("_");
2340
+ }
2341
+ function toCamelCase(input) {
2342
+ const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
2343
+ return words.reduce((acc, word, i) => {
2344
+ const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
2345
+ return acc + formattedWord;
2346
+ }, "");
2347
+ }
2348
+ function noopCase(input) {
2349
+ return input;
2350
+ }
2351
+
2352
+ class CasingCache {
2353
+ static [entityKind] = "CasingCache";
2354
+ cache = {};
2355
+ cachedTables = {};
2356
+ convert;
2357
+ constructor(casing) {
2358
+ this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase;
2359
+ }
2360
+ getColumnCasing(column) {
2361
+ if (!column.keyAsName)
2362
+ return column.name;
2363
+ const schema = column.table[Table.Symbol.Schema] ?? "public";
2364
+ const tableName = column.table[Table.Symbol.OriginalName];
2365
+ const key = `${schema}.${tableName}.${column.name}`;
2366
+ if (!this.cache[key]) {
2367
+ this.cacheTable(column.table);
2368
+ }
2369
+ return this.cache[key];
2370
+ }
2371
+ cacheTable(table) {
2372
+ const schema = table[Table.Symbol.Schema] ?? "public";
2373
+ const tableName = table[Table.Symbol.OriginalName];
2374
+ const tableKey = `${schema}.${tableName}`;
2375
+ if (!this.cachedTables[tableKey]) {
2376
+ for (const column of Object.values(table[Table.Symbol.Columns])) {
2377
+ const columnKey = `${tableKey}.${column.name}`;
2378
+ this.cache[columnKey] = this.convert(column.name);
2379
+ }
2380
+ this.cachedTables[tableKey] = true;
2381
+ }
2382
+ }
2383
+ clearCache() {
2384
+ this.cache = {};
2385
+ this.cachedTables = {};
2386
+ }
2387
+ }
2388
+
2389
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/errors.js
2390
+ class DrizzleError extends Error {
2391
+ static [entityKind] = "DrizzleError";
2392
+ constructor({ message, cause }) {
2393
+ super(message);
2394
+ this.name = "DrizzleError";
2395
+ this.cause = cause;
2396
+ }
2397
+ }
2398
+
2399
+ class TransactionRollbackError extends DrizzleError {
2400
+ static [entityKind] = "TransactionRollbackError";
2401
+ constructor() {
2402
+ super({ message: "Rollback" });
2403
+ }
2404
+ }
2405
+
2406
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/view-base.js
2407
+ class SQLiteViewBase extends View {
2408
+ static [entityKind] = "SQLiteViewBase";
2409
+ }
2410
+
2411
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/dialect.js
2412
+ class SQLiteDialect {
2413
+ static [entityKind] = "SQLiteDialect";
2414
+ casing;
2415
+ constructor(config) {
2416
+ this.casing = new CasingCache(config?.casing);
2417
+ }
2418
+ escapeName(name) {
2419
+ return `"${name}"`;
2420
+ }
2421
+ escapeParam(_num) {
2422
+ return "?";
2423
+ }
2424
+ escapeString(str) {
2425
+ return `'${str.replace(/'/g, "''")}'`;
2426
+ }
2427
+ buildWithCTE(queries) {
2428
+ if (!queries?.length)
2429
+ return;
2430
+ const withSqlChunks = [sql`with `];
2431
+ for (const [i, w] of queries.entries()) {
2432
+ withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
2433
+ if (i < queries.length - 1) {
2434
+ withSqlChunks.push(sql`, `);
2435
+ }
2436
+ }
2437
+ withSqlChunks.push(sql` `);
2438
+ return sql.join(withSqlChunks);
2439
+ }
2440
+ buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) {
2441
+ const withSql = this.buildWithCTE(withList);
2442
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2443
+ const whereSql = where ? sql` where ${where}` : undefined;
2444
+ const orderBySql = this.buildOrderBy(orderBy);
2445
+ const limitSql = this.buildLimit(limit);
2446
+ return sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`;
2447
+ }
2448
+ buildUpdateSet(table, set) {
2449
+ const tableColumns = table[Table.Symbol.Columns];
2450
+ const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined);
2451
+ const setSize = columnNames.length;
2452
+ return sql.join(columnNames.flatMap((colName, i) => {
2453
+ const col = tableColumns[colName];
2454
+ const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
2455
+ const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
2456
+ if (i < setSize - 1) {
2457
+ return [res, sql.raw(", ")];
2458
+ }
2459
+ return [res];
2460
+ }));
2461
+ }
2462
+ buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) {
2463
+ const withSql = this.buildWithCTE(withList);
2464
+ const setSql = this.buildUpdateSet(table, set);
2465
+ const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
2466
+ const joinsSql = this.buildJoins(joins);
2467
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2468
+ const whereSql = where ? sql` where ${where}` : undefined;
2469
+ const orderBySql = this.buildOrderBy(orderBy);
2470
+ const limitSql = this.buildLimit(limit);
2471
+ return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
2472
+ }
2473
+ buildSelection(fields, { isSingleTable = false } = {}) {
2474
+ const columnsLen = fields.length;
2475
+ const chunks = fields.flatMap(({ field }, i) => {
2476
+ const chunk = [];
2477
+ if (is(field, SQL.Aliased) && field.isSelectionField) {
2478
+ chunk.push(sql.identifier(field.fieldAlias));
2479
+ } else if (is(field, SQL.Aliased) || is(field, SQL)) {
2480
+ const query = is(field, SQL.Aliased) ? field.sql : field;
2481
+ if (isSingleTable) {
2482
+ chunk.push(new SQL(query.queryChunks.map((c2) => {
2483
+ if (is(c2, Column)) {
2484
+ return sql.identifier(this.casing.getColumnCasing(c2));
2485
+ }
2486
+ return c2;
2487
+ })));
2488
+ } else {
2489
+ chunk.push(query);
2490
+ }
2491
+ if (is(field, SQL.Aliased)) {
2492
+ chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
2493
+ }
2494
+ } else if (is(field, Column)) {
2495
+ const tableName = field.table[Table.Symbol.Name];
2496
+ if (isSingleTable) {
2497
+ chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
2498
+ } else {
2499
+ chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
2500
+ }
2501
+ }
2502
+ if (i < columnsLen - 1) {
2503
+ chunk.push(sql`, `);
2504
+ }
2505
+ return chunk;
2506
+ });
2507
+ return sql.join(chunks);
2508
+ }
2509
+ buildJoins(joins) {
2510
+ if (!joins || joins.length === 0) {
2511
+ return;
2512
+ }
2513
+ const joinsArray = [];
2514
+ if (joins) {
2515
+ for (const [index, joinMeta] of joins.entries()) {
2516
+ if (index === 0) {
2517
+ joinsArray.push(sql` `);
2518
+ }
2519
+ const table = joinMeta.table;
2520
+ if (is(table, SQLiteTable)) {
2521
+ const tableName = table[SQLiteTable.Symbol.Name];
2522
+ const tableSchema = table[SQLiteTable.Symbol.Schema];
2523
+ const origTableName = table[SQLiteTable.Symbol.OriginalName];
2524
+ const alias = tableName === origTableName ? undefined : joinMeta.alias;
2525
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`);
2526
+ } else {
2527
+ joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join ${table} on ${joinMeta.on}`);
2528
+ }
2529
+ if (index < joins.length - 1) {
2530
+ joinsArray.push(sql` `);
2531
+ }
2532
+ }
2533
+ }
2534
+ return sql.join(joinsArray);
2535
+ }
2536
+ buildLimit(limit) {
2537
+ return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
2538
+ }
2539
+ buildOrderBy(orderBy) {
2540
+ const orderByList = [];
2541
+ if (orderBy) {
2542
+ for (const [index, orderByValue] of orderBy.entries()) {
2543
+ orderByList.push(orderByValue);
2544
+ if (index < orderBy.length - 1) {
2545
+ orderByList.push(sql`, `);
2546
+ }
2547
+ }
2548
+ }
2549
+ return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : undefined;
2550
+ }
2551
+ buildFromTable(table) {
2552
+ if (is(table, Table) && table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]) {
2553
+ return sql`${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
2554
+ }
2555
+ return table;
2556
+ }
2557
+ buildSelectQuery({
2558
+ withList,
2559
+ fields,
2560
+ fieldsFlat,
2561
+ where,
2562
+ having,
2563
+ table,
2564
+ joins,
2565
+ orderBy,
2566
+ groupBy,
2567
+ limit,
2568
+ offset,
2569
+ distinct,
2570
+ setOperators
2571
+ }) {
2572
+ const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
2573
+ for (const f2 of fieldsList) {
2574
+ if (is(f2.field, Column) && getTableName(f2.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f2.field.table)) {
2575
+ const tableName = getTableName(f2.field.table);
2576
+ throw new Error(`Your "${f2.path.join("->")}" field references a column "${tableName}"."${f2.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`);
2577
+ }
2578
+ }
2579
+ const isSingleTable = !joins || joins.length === 0;
2580
+ const withSql = this.buildWithCTE(withList);
2581
+ const distinctSql = distinct ? sql` distinct` : undefined;
2582
+ const selection = this.buildSelection(fieldsList, { isSingleTable });
2583
+ const tableSql = this.buildFromTable(table);
2584
+ const joinsSql = this.buildJoins(joins);
2585
+ const whereSql = where ? sql` where ${where}` : undefined;
2586
+ const havingSql = having ? sql` having ${having}` : undefined;
2587
+ const groupByList = [];
2588
+ if (groupBy) {
2589
+ for (const [index, groupByValue] of groupBy.entries()) {
2590
+ groupByList.push(groupByValue);
2591
+ if (index < groupBy.length - 1) {
2592
+ groupByList.push(sql`, `);
2593
+ }
2594
+ }
2595
+ }
2596
+ const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : undefined;
2597
+ const orderBySql = this.buildOrderBy(orderBy);
2598
+ const limitSql = this.buildLimit(limit);
2599
+ const offsetSql = offset ? sql` offset ${offset}` : undefined;
2600
+ const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
2601
+ if (setOperators.length > 0) {
2602
+ return this.buildSetOperations(finalQuery, setOperators);
2603
+ }
2604
+ return finalQuery;
2605
+ }
2606
+ buildSetOperations(leftSelect, setOperators) {
2607
+ const [setOperator, ...rest] = setOperators;
2608
+ if (!setOperator) {
2609
+ throw new Error("Cannot pass undefined values to any set operator");
2610
+ }
2611
+ if (rest.length === 0) {
2612
+ return this.buildSetOperationQuery({ leftSelect, setOperator });
2613
+ }
2614
+ return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest);
2615
+ }
2616
+ buildSetOperationQuery({
2617
+ leftSelect,
2618
+ setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
2619
+ }) {
2620
+ const leftChunk = sql`${leftSelect.getSQL()} `;
2621
+ const rightChunk = sql`${rightSelect.getSQL()}`;
2622
+ let orderBySql;
2623
+ if (orderBy && orderBy.length > 0) {
2624
+ const orderByValues = [];
2625
+ for (const singleOrderBy of orderBy) {
2626
+ if (is(singleOrderBy, SQLiteColumn)) {
2627
+ orderByValues.push(sql.identifier(singleOrderBy.name));
2628
+ } else if (is(singleOrderBy, SQL)) {
2629
+ for (let i = 0;i < singleOrderBy.queryChunks.length; i++) {
2630
+ const chunk = singleOrderBy.queryChunks[i];
2631
+ if (is(chunk, SQLiteColumn)) {
2632
+ singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
2633
+ }
2634
+ }
2635
+ orderByValues.push(sql`${singleOrderBy}`);
2636
+ } else {
2637
+ orderByValues.push(sql`${singleOrderBy}`);
2638
+ }
2639
+ }
2640
+ orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
2641
+ }
2642
+ const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined;
2643
+ const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
2644
+ const offsetSql = offset ? sql` offset ${offset}` : undefined;
2645
+ return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
2646
+ }
2647
+ buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) {
2648
+ const valuesSqlList = [];
2649
+ const columns = table[Table.Symbol.Columns];
2650
+ const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert());
2651
+ const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));
2652
+ if (select) {
2653
+ const select2 = valuesOrSelect;
2654
+ if (is(select2, SQL)) {
2655
+ valuesSqlList.push(select2);
2656
+ } else {
2657
+ valuesSqlList.push(select2.getSQL());
2658
+ }
2659
+ } else {
2660
+ const values = valuesOrSelect;
2661
+ valuesSqlList.push(sql.raw("values "));
2662
+ for (const [valueIndex, value] of values.entries()) {
2663
+ const valueList = [];
2664
+ for (const [fieldName, col] of colEntries) {
2665
+ const colValue = value[fieldName];
2666
+ if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) {
2667
+ let defaultValue;
2668
+ if (col.default !== null && col.default !== undefined) {
2669
+ defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
2670
+ } else if (col.defaultFn !== undefined) {
2671
+ const defaultFnResult = col.defaultFn();
2672
+ defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
2673
+ } else if (!col.default && col.onUpdateFn !== undefined) {
2674
+ const onUpdateFnResult = col.onUpdateFn();
2675
+ defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
2676
+ } else {
2677
+ defaultValue = sql`null`;
2678
+ }
2679
+ valueList.push(defaultValue);
2680
+ } else {
2681
+ valueList.push(colValue);
2682
+ }
2683
+ }
2684
+ valuesSqlList.push(valueList);
2685
+ if (valueIndex < values.length - 1) {
2686
+ valuesSqlList.push(sql`, `);
2687
+ }
2688
+ }
2689
+ }
2690
+ const withSql = this.buildWithCTE(withList);
2691
+ const valuesSql = sql.join(valuesSqlList);
2692
+ const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined;
2693
+ const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined;
2694
+ return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
2695
+ }
2696
+ sqlToQuery(sql2, invokeSource) {
2697
+ return sql2.toQuery({
2698
+ casing: this.casing,
2699
+ escapeName: this.escapeName,
2700
+ escapeParam: this.escapeParam,
2701
+ escapeString: this.escapeString,
2702
+ invokeSource
2703
+ });
2704
+ }
2705
+ buildRelationalQuery({
2706
+ fullSchema,
2707
+ schema,
2708
+ tableNamesMap,
2709
+ table,
2710
+ tableConfig,
2711
+ queryConfig: config,
2712
+ tableAlias,
2713
+ nestedQueryRelation,
2714
+ joinOn
2715
+ }) {
2716
+ let selection = [];
2717
+ let limit, offset, orderBy = [], where;
2718
+ const joins = [];
2719
+ if (config === true) {
2720
+ const selectionEntries = Object.entries(tableConfig.columns);
2721
+ selection = selectionEntries.map(([key, value]) => ({
2722
+ dbKey: value.name,
2723
+ tsKey: key,
2724
+ field: aliasedTableColumn(value, tableAlias),
2725
+ relationTableTsKey: undefined,
2726
+ isJson: false,
2727
+ selection: []
2728
+ }));
2729
+ } else {
2730
+ const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]));
2731
+ if (config.where) {
2732
+ const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
2733
+ where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
2734
+ }
2735
+ const fieldsSelection = [];
2736
+ let selectedColumns = [];
2737
+ if (config.columns) {
2738
+ let isIncludeMode = false;
2739
+ for (const [field, value] of Object.entries(config.columns)) {
2740
+ if (value === undefined) {
2741
+ continue;
2742
+ }
2743
+ if (field in tableConfig.columns) {
2744
+ if (!isIncludeMode && value === true) {
2745
+ isIncludeMode = true;
2746
+ }
2747
+ selectedColumns.push(field);
2748
+ }
2749
+ }
2750
+ if (selectedColumns.length > 0) {
2751
+ selectedColumns = isIncludeMode ? selectedColumns.filter((c2) => config.columns?.[c2] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
2752
+ }
2753
+ } else {
2754
+ selectedColumns = Object.keys(tableConfig.columns);
2755
+ }
2756
+ for (const field of selectedColumns) {
2757
+ const column = tableConfig.columns[field];
2758
+ fieldsSelection.push({ tsKey: field, value: column });
2759
+ }
2760
+ let selectedRelations = [];
2761
+ if (config.with) {
2762
+ selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
2763
+ }
2764
+ let extras;
2765
+ if (config.extras) {
2766
+ extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
2767
+ for (const [tsKey, value] of Object.entries(extras)) {
2768
+ fieldsSelection.push({
2769
+ tsKey,
2770
+ value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
2771
+ });
2772
+ }
2773
+ }
2774
+ for (const { tsKey, value } of fieldsSelection) {
2775
+ selection.push({
2776
+ dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
2777
+ tsKey,
2778
+ field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
2779
+ relationTableTsKey: undefined,
2780
+ isJson: false,
2781
+ selection: []
2782
+ });
2783
+ }
2784
+ let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
2785
+ if (!Array.isArray(orderByOrig)) {
2786
+ orderByOrig = [orderByOrig];
2787
+ }
2788
+ orderBy = orderByOrig.map((orderByValue) => {
2789
+ if (is(orderByValue, Column)) {
2790
+ return aliasedTableColumn(orderByValue, tableAlias);
2791
+ }
2792
+ return mapColumnsInSQLToAlias(orderByValue, tableAlias);
2793
+ });
2794
+ limit = config.limit;
2795
+ offset = config.offset;
2796
+ for (const {
2797
+ tsKey: selectedRelationTsKey,
2798
+ queryConfig: selectedRelationConfigValue,
2799
+ relation
2800
+ } of selectedRelations) {
2801
+ const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
2802
+ const relationTableName = getTableUniqueName(relation.referencedTable);
2803
+ const relationTableTsName = tableNamesMap[relationTableName];
2804
+ const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
2805
+ const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias))));
2806
+ const builtRelation = this.buildRelationalQuery({
2807
+ fullSchema,
2808
+ schema,
2809
+ tableNamesMap,
2810
+ table: fullSchema[relationTableTsName],
2811
+ tableConfig: schema[relationTableTsName],
2812
+ queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
2813
+ tableAlias: relationTableAlias,
2814
+ joinOn: joinOn2,
2815
+ nestedQueryRelation: relation
2816
+ });
2817
+ const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
2818
+ selection.push({
2819
+ dbKey: selectedRelationTsKey,
2820
+ tsKey: selectedRelationTsKey,
2821
+ field,
2822
+ relationTableTsKey: relationTableTsName,
2823
+ isJson: true,
2824
+ selection: builtRelation.selection
2825
+ });
2826
+ }
2827
+ }
2828
+ if (selection.length === 0) {
2829
+ throw new DrizzleError({
2830
+ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
2831
+ });
2832
+ }
2833
+ let result;
2834
+ where = and(joinOn, where);
2835
+ if (nestedQueryRelation) {
2836
+ let field = sql`json_array(${sql.join(selection.map(({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`;
2837
+ if (is(nestedQueryRelation, Many)) {
2838
+ field = sql`coalesce(json_group_array(${field}), json_array())`;
2839
+ }
2840
+ const nestedSelection = [{
2841
+ dbKey: "data",
2842
+ tsKey: "data",
2843
+ field: field.as("data"),
2844
+ isJson: true,
2845
+ relationTableTsKey: tableConfig.tsName,
2846
+ selection
2847
+ }];
2848
+ const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;
2849
+ if (needsSubquery) {
2850
+ result = this.buildSelectQuery({
2851
+ table: aliasedTable(table, tableAlias),
2852
+ fields: {},
2853
+ fieldsFlat: [
2854
+ {
2855
+ path: [],
2856
+ field: sql.raw("*")
2857
+ }
2858
+ ],
2859
+ where,
2860
+ limit,
2861
+ offset,
2862
+ orderBy,
2863
+ setOperators: []
2864
+ });
2865
+ where = undefined;
2866
+ limit = undefined;
2867
+ offset = undefined;
2868
+ orderBy = undefined;
2869
+ } else {
2870
+ result = aliasedTable(table, tableAlias);
2871
+ }
2872
+ result = this.buildSelectQuery({
2873
+ table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
2874
+ fields: {},
2875
+ fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
2876
+ path: [],
2877
+ field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2
2878
+ })),
2879
+ joins,
2880
+ where,
2881
+ limit,
2882
+ offset,
2883
+ orderBy,
2884
+ setOperators: []
2885
+ });
2886
+ } else {
2887
+ result = this.buildSelectQuery({
2888
+ table: aliasedTable(table, tableAlias),
2889
+ fields: {},
2890
+ fieldsFlat: selection.map(({ field }) => ({
2891
+ path: [],
2892
+ field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field
2893
+ })),
2894
+ joins,
2895
+ where,
2896
+ limit,
2897
+ offset,
2898
+ orderBy,
2899
+ setOperators: []
2900
+ });
2901
+ }
2902
+ return {
2903
+ tableTsKey: tableConfig.tsName,
2904
+ sql: result,
2905
+ selection
2906
+ };
2907
+ }
2908
+ }
2909
+
2910
+ class SQLiteSyncDialect extends SQLiteDialect {
2911
+ static [entityKind] = "SQLiteSyncDialect";
2912
+ migrate(migrations, session, config) {
2913
+ const migrationsTable = config === undefined ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
2914
+ const migrationTableCreate = sql`
2915
+ CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
2916
+ id SERIAL PRIMARY KEY,
2917
+ hash text NOT NULL,
2918
+ created_at numeric
2919
+ )
2920
+ `;
2921
+ session.run(migrationTableCreate);
2922
+ const dbMigrations = session.values(sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`);
2923
+ const lastDbMigration = dbMigrations[0] ?? undefined;
2924
+ session.run(sql`BEGIN`);
2925
+ try {
2926
+ for (const migration of migrations) {
2927
+ if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
2928
+ for (const stmt of migration.sql) {
2929
+ session.run(sql.raw(stmt));
2930
+ }
2931
+ session.run(sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`);
2932
+ }
2933
+ }
2934
+ session.run(sql`COMMIT`);
2935
+ } catch (e2) {
2936
+ session.run(sql`ROLLBACK`);
2937
+ throw e2;
2938
+ }
2939
+ }
2940
+ }
2941
+
2942
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/query-builders/query-builder.js
2943
+ class TypedQueryBuilder {
2944
+ static [entityKind] = "TypedQueryBuilder";
2945
+ getSelectedFields() {
2946
+ return this._.selectedFields;
2947
+ }
2948
+ }
2949
+
2950
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/select.js
2951
+ class SQLiteSelectBuilder {
2952
+ static [entityKind] = "SQLiteSelectBuilder";
2953
+ fields;
2954
+ session;
2955
+ dialect;
2956
+ withList;
2957
+ distinct;
2958
+ constructor(config) {
2959
+ this.fields = config.fields;
2960
+ this.session = config.session;
2961
+ this.dialect = config.dialect;
2962
+ this.withList = config.withList;
2963
+ this.distinct = config.distinct;
2964
+ }
2965
+ from(source) {
2966
+ const isPartialSelect = !!this.fields;
2967
+ let fields;
2968
+ if (this.fields) {
2969
+ fields = this.fields;
2970
+ } else if (is(source, Subquery)) {
2971
+ fields = Object.fromEntries(Object.keys(source._.selectedFields).map((key) => [key, source[key]]));
2972
+ } else if (is(source, SQLiteViewBase)) {
2973
+ fields = source[ViewBaseConfig].selectedFields;
2974
+ } else if (is(source, SQL)) {
2975
+ fields = {};
2976
+ } else {
2977
+ fields = getTableColumns(source);
2978
+ }
2979
+ return new SQLiteSelectBase({
2980
+ table: source,
2981
+ fields,
2982
+ isPartialSelect,
2983
+ session: this.session,
2984
+ dialect: this.dialect,
2985
+ withList: this.withList,
2986
+ distinct: this.distinct
2987
+ });
2988
+ }
2989
+ }
2990
+
2991
+ class SQLiteSelectQueryBuilderBase extends TypedQueryBuilder {
2992
+ static [entityKind] = "SQLiteSelectQueryBuilder";
2993
+ _;
2994
+ config;
2995
+ joinsNotNullableMap;
2996
+ tableName;
2997
+ isPartialSelect;
2998
+ session;
2999
+ dialect;
3000
+ constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) {
3001
+ super();
3002
+ this.config = {
3003
+ withList,
3004
+ table,
3005
+ fields: { ...fields },
3006
+ distinct,
3007
+ setOperators: []
3008
+ };
3009
+ this.isPartialSelect = isPartialSelect;
3010
+ this.session = session;
3011
+ this.dialect = dialect;
3012
+ this._ = {
3013
+ selectedFields: fields
3014
+ };
3015
+ this.tableName = getTableLikeName(table);
3016
+ this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
3017
+ }
3018
+ createJoin(joinType) {
3019
+ return (table, on) => {
3020
+ const baseTableName = this.tableName;
3021
+ const tableName = getTableLikeName(table);
3022
+ if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
3023
+ throw new Error(`Alias "${tableName}" is already used in this query`);
3024
+ }
3025
+ if (!this.isPartialSelect) {
3026
+ if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
3027
+ this.config.fields = {
3028
+ [baseTableName]: this.config.fields
3029
+ };
3030
+ }
3031
+ if (typeof tableName === "string" && !is(table, SQL)) {
3032
+ const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];
3033
+ this.config.fields[tableName] = selection;
3034
+ }
3035
+ }
3036
+ if (typeof on === "function") {
3037
+ on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3038
+ }
3039
+ if (!this.config.joins) {
3040
+ this.config.joins = [];
3041
+ }
3042
+ this.config.joins.push({ on, table, joinType, alias: tableName });
3043
+ if (typeof tableName === "string") {
3044
+ switch (joinType) {
3045
+ case "left": {
3046
+ this.joinsNotNullableMap[tableName] = false;
3047
+ break;
3048
+ }
3049
+ case "right": {
3050
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
3051
+ this.joinsNotNullableMap[tableName] = true;
3052
+ break;
3053
+ }
3054
+ case "inner": {
3055
+ this.joinsNotNullableMap[tableName] = true;
3056
+ break;
3057
+ }
3058
+ case "full": {
3059
+ this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));
3060
+ this.joinsNotNullableMap[tableName] = false;
3061
+ break;
3062
+ }
3063
+ }
3064
+ }
3065
+ return this;
3066
+ };
3067
+ }
3068
+ leftJoin = this.createJoin("left");
3069
+ rightJoin = this.createJoin("right");
3070
+ innerJoin = this.createJoin("inner");
3071
+ fullJoin = this.createJoin("full");
3072
+ createSetOperator(type, isAll) {
3073
+ return (rightSelection) => {
3074
+ const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
3075
+ if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
3076
+ throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3077
+ }
3078
+ this.config.setOperators.push({ type, isAll, rightSelect });
3079
+ return this;
3080
+ };
3081
+ }
3082
+ union = this.createSetOperator("union", false);
3083
+ unionAll = this.createSetOperator("union", true);
3084
+ intersect = this.createSetOperator("intersect", false);
3085
+ except = this.createSetOperator("except", false);
3086
+ addSetOperators(setOperators) {
3087
+ this.config.setOperators.push(...setOperators);
3088
+ return this;
3089
+ }
3090
+ where(where) {
3091
+ if (typeof where === "function") {
3092
+ where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3093
+ }
3094
+ this.config.where = where;
3095
+ return this;
3096
+ }
3097
+ having(having) {
3098
+ if (typeof having === "function") {
3099
+ having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3100
+ }
3101
+ this.config.having = having;
3102
+ return this;
3103
+ }
3104
+ groupBy(...columns) {
3105
+ if (typeof columns[0] === "function") {
3106
+ const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3107
+ this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
3108
+ } else {
3109
+ this.config.groupBy = columns;
3110
+ }
3111
+ return this;
3112
+ }
3113
+ orderBy(...columns) {
3114
+ if (typeof columns[0] === "function") {
3115
+ const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3116
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3117
+ if (this.config.setOperators.length > 0) {
3118
+ this.config.setOperators.at(-1).orderBy = orderByArray;
3119
+ } else {
3120
+ this.config.orderBy = orderByArray;
3121
+ }
3122
+ } else {
3123
+ const orderByArray = columns;
3124
+ if (this.config.setOperators.length > 0) {
3125
+ this.config.setOperators.at(-1).orderBy = orderByArray;
3126
+ } else {
3127
+ this.config.orderBy = orderByArray;
3128
+ }
3129
+ }
3130
+ return this;
3131
+ }
3132
+ limit(limit) {
3133
+ if (this.config.setOperators.length > 0) {
3134
+ this.config.setOperators.at(-1).limit = limit;
3135
+ } else {
3136
+ this.config.limit = limit;
3137
+ }
3138
+ return this;
3139
+ }
3140
+ offset(offset) {
3141
+ if (this.config.setOperators.length > 0) {
3142
+ this.config.setOperators.at(-1).offset = offset;
3143
+ } else {
3144
+ this.config.offset = offset;
3145
+ }
3146
+ return this;
3147
+ }
3148
+ getSQL() {
3149
+ return this.dialect.buildSelectQuery(this.config);
3150
+ }
3151
+ toSQL() {
3152
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3153
+ return rest;
3154
+ }
3155
+ as(alias) {
3156
+ return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3157
+ }
3158
+ getSelectedFields() {
3159
+ return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3160
+ }
3161
+ $dynamic() {
3162
+ return this;
3163
+ }
3164
+ }
3165
+
3166
+ class SQLiteSelectBase extends SQLiteSelectQueryBuilderBase {
3167
+ static [entityKind] = "SQLiteSelect";
3168
+ _prepare(isOneTimeQuery = true) {
3169
+ if (!this.session) {
3170
+ throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
3171
+ }
3172
+ const fieldsList = orderSelectedFields(this.config.fields);
3173
+ const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all", true);
3174
+ query.joinsNotNullableMap = this.joinsNotNullableMap;
3175
+ return query;
3176
+ }
3177
+ prepare() {
3178
+ return this._prepare(false);
3179
+ }
3180
+ run = (placeholderValues) => {
3181
+ return this._prepare().run(placeholderValues);
3182
+ };
3183
+ all = (placeholderValues) => {
3184
+ return this._prepare().all(placeholderValues);
3185
+ };
3186
+ get = (placeholderValues) => {
3187
+ return this._prepare().get(placeholderValues);
3188
+ };
3189
+ values = (placeholderValues) => {
3190
+ return this._prepare().values(placeholderValues);
3191
+ };
3192
+ async execute() {
3193
+ return this.all();
3194
+ }
3195
+ }
3196
+ applyMixins(SQLiteSelectBase, [QueryPromise]);
3197
+ function createSetOperator(type, isAll) {
3198
+ return (leftSelect, rightSelect, ...restSelects) => {
3199
+ const setOperators = [rightSelect, ...restSelects].map((select) => ({
3200
+ type,
3201
+ isAll,
3202
+ rightSelect: select
3203
+ }));
3204
+ for (const setOperator of setOperators) {
3205
+ if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
3206
+ throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");
3207
+ }
3208
+ }
3209
+ return leftSelect.addSetOperators(setOperators);
3210
+ };
3211
+ }
3212
+ var getSQLiteSetOperators = () => ({
3213
+ union,
3214
+ unionAll,
3215
+ intersect,
3216
+ except
3217
+ });
3218
+ var union = createSetOperator("union", false);
3219
+ var unionAll = createSetOperator("union", true);
3220
+ var intersect = createSetOperator("intersect", false);
3221
+ var except = createSetOperator("except", false);
3222
+
3223
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
3224
+ class QueryBuilder {
3225
+ static [entityKind] = "SQLiteQueryBuilder";
3226
+ dialect;
3227
+ dialectConfig;
3228
+ constructor(dialect) {
3229
+ this.dialect = is(dialect, SQLiteDialect) ? dialect : undefined;
3230
+ this.dialectConfig = is(dialect, SQLiteDialect) ? undefined : dialect;
3231
+ }
3232
+ $with(alias) {
3233
+ const queryBuilder = this;
3234
+ return {
3235
+ as(qb) {
3236
+ if (typeof qb === "function") {
3237
+ qb = qb(queryBuilder);
3238
+ }
3239
+ return new Proxy(new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3240
+ }
3241
+ };
3242
+ }
3243
+ with(...queries) {
3244
+ const self = this;
3245
+ function select(fields) {
3246
+ return new SQLiteSelectBuilder({
3247
+ fields: fields ?? undefined,
3248
+ session: undefined,
3249
+ dialect: self.getDialect(),
3250
+ withList: queries
3251
+ });
3252
+ }
3253
+ function selectDistinct(fields) {
3254
+ return new SQLiteSelectBuilder({
3255
+ fields: fields ?? undefined,
3256
+ session: undefined,
3257
+ dialect: self.getDialect(),
3258
+ withList: queries,
3259
+ distinct: true
3260
+ });
3261
+ }
3262
+ return { select, selectDistinct };
3263
+ }
3264
+ select(fields) {
3265
+ return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: undefined, dialect: this.getDialect() });
3266
+ }
3267
+ selectDistinct(fields) {
3268
+ return new SQLiteSelectBuilder({
3269
+ fields: fields ?? undefined,
3270
+ session: undefined,
3271
+ dialect: this.getDialect(),
3272
+ distinct: true
3273
+ });
3274
+ }
3275
+ getDialect() {
3276
+ if (!this.dialect) {
3277
+ this.dialect = new SQLiteSyncDialect(this.dialectConfig);
3278
+ }
3279
+ return this.dialect;
3280
+ }
3281
+ }
3282
+
3283
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
3284
+ class SQLiteInsertBuilder {
3285
+ constructor(table, session, dialect, withList) {
3286
+ this.table = table;
3287
+ this.session = session;
3288
+ this.dialect = dialect;
3289
+ this.withList = withList;
3290
+ }
3291
+ static [entityKind] = "SQLiteInsertBuilder";
3292
+ values(values) {
3293
+ values = Array.isArray(values) ? values : [values];
3294
+ if (values.length === 0) {
3295
+ throw new Error("values() must be called with at least one value");
3296
+ }
3297
+ const mappedValues = values.map((entry) => {
3298
+ const result = {};
3299
+ const cols = this.table[Table.Symbol.Columns];
3300
+ for (const colKey of Object.keys(entry)) {
3301
+ const colValue = entry[colKey];
3302
+ result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
3303
+ }
3304
+ return result;
3305
+ });
3306
+ return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
3307
+ }
3308
+ select(selectQuery) {
3309
+ const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery;
3310
+ if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
3311
+ throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");
3312
+ }
3313
+ return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
3314
+ }
3315
+ }
3316
+
3317
+ class SQLiteInsertBase extends QueryPromise {
3318
+ constructor(table, values, session, dialect, withList, select) {
3319
+ super();
3320
+ this.session = session;
3321
+ this.dialect = dialect;
3322
+ this.config = { table, values, withList, select };
3323
+ }
3324
+ static [entityKind] = "SQLiteInsert";
3325
+ config;
3326
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3327
+ this.config.returning = orderSelectedFields(fields);
3328
+ return this;
3329
+ }
3330
+ onConflictDoNothing(config = {}) {
3331
+ if (config.target === undefined) {
3332
+ this.config.onConflict = sql`do nothing`;
3333
+ } else {
3334
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3335
+ const whereSql = config.where ? sql` where ${config.where}` : sql``;
3336
+ this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
3337
+ }
3338
+ return this;
3339
+ }
3340
+ onConflictDoUpdate(config) {
3341
+ if (config.where && (config.targetWhere || config.setWhere)) {
3342
+ throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');
3343
+ }
3344
+ const whereSql = config.where ? sql` where ${config.where}` : undefined;
3345
+ const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;
3346
+ const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;
3347
+ const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
3348
+ const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
3349
+ this.config.onConflict = sql`${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
3350
+ return this;
3351
+ }
3352
+ getSQL() {
3353
+ return this.dialect.buildInsertQuery(this.config);
3354
+ }
3355
+ toSQL() {
3356
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3357
+ return rest;
3358
+ }
3359
+ _prepare(isOneTimeQuery = true) {
3360
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
3361
+ }
3362
+ prepare() {
3363
+ return this._prepare(false);
3364
+ }
3365
+ run = (placeholderValues) => {
3366
+ return this._prepare().run(placeholderValues);
3367
+ };
3368
+ all = (placeholderValues) => {
3369
+ return this._prepare().all(placeholderValues);
3370
+ };
3371
+ get = (placeholderValues) => {
3372
+ return this._prepare().get(placeholderValues);
3373
+ };
3374
+ values = (placeholderValues) => {
3375
+ return this._prepare().values(placeholderValues);
3376
+ };
3377
+ async execute() {
3378
+ return this.config.returning ? this.all() : this.run();
3379
+ }
3380
+ $dynamic() {
3381
+ return this;
3382
+ }
3383
+ }
3384
+
3385
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/update.js
3386
+ class SQLiteUpdateBuilder {
3387
+ constructor(table, session, dialect, withList) {
3388
+ this.table = table;
3389
+ this.session = session;
3390
+ this.dialect = dialect;
3391
+ this.withList = withList;
3392
+ }
3393
+ static [entityKind] = "SQLiteUpdateBuilder";
3394
+ set(values) {
3395
+ return new SQLiteUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
3396
+ }
3397
+ }
3398
+
3399
+ class SQLiteUpdateBase extends QueryPromise {
3400
+ constructor(table, set, session, dialect, withList) {
3401
+ super();
3402
+ this.session = session;
3403
+ this.dialect = dialect;
3404
+ this.config = { set, table, withList, joins: [] };
3405
+ }
3406
+ static [entityKind] = "SQLiteUpdate";
3407
+ config;
3408
+ from(source) {
3409
+ this.config.from = source;
3410
+ return this;
3411
+ }
3412
+ createJoin(joinType) {
3413
+ return (table, on) => {
3414
+ const tableName = getTableLikeName(table);
3415
+ if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
3416
+ throw new Error(`Alias "${tableName}" is already used in this query`);
3417
+ }
3418
+ if (typeof on === "function") {
3419
+ const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : undefined : undefined;
3420
+ on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })));
3421
+ }
3422
+ this.config.joins.push({ on, table, joinType, alias: tableName });
3423
+ return this;
3424
+ };
3425
+ }
3426
+ leftJoin = this.createJoin("left");
3427
+ rightJoin = this.createJoin("right");
3428
+ innerJoin = this.createJoin("inner");
3429
+ fullJoin = this.createJoin("full");
3430
+ where(where) {
3431
+ this.config.where = where;
3432
+ return this;
3433
+ }
3434
+ orderBy(...columns) {
3435
+ if (typeof columns[0] === "function") {
3436
+ const orderBy = columns[0](new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })));
3437
+ const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
3438
+ this.config.orderBy = orderByArray;
3439
+ } else {
3440
+ const orderByArray = columns;
3441
+ this.config.orderBy = orderByArray;
3442
+ }
3443
+ return this;
3444
+ }
3445
+ limit(limit) {
3446
+ this.config.limit = limit;
3447
+ return this;
3448
+ }
3449
+ returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
3450
+ this.config.returning = orderSelectedFields(fields);
3451
+ return this;
3452
+ }
3453
+ getSQL() {
3454
+ return this.dialect.buildUpdateQuery(this.config);
3455
+ }
3456
+ toSQL() {
3457
+ const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
3458
+ return rest;
3459
+ }
3460
+ _prepare(isOneTimeQuery = true) {
3461
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](this.dialect.sqlToQuery(this.getSQL()), this.config.returning, this.config.returning ? "all" : "run", true);
3462
+ }
3463
+ prepare() {
3464
+ return this._prepare(false);
3465
+ }
3466
+ run = (placeholderValues) => {
3467
+ return this._prepare().run(placeholderValues);
3468
+ };
3469
+ all = (placeholderValues) => {
3470
+ return this._prepare().all(placeholderValues);
3471
+ };
3472
+ get = (placeholderValues) => {
3473
+ return this._prepare().get(placeholderValues);
3474
+ };
3475
+ values = (placeholderValues) => {
3476
+ return this._prepare().values(placeholderValues);
3477
+ };
3478
+ async execute() {
3479
+ return this.config.returning ? this.all() : this.run();
3480
+ }
3481
+ $dynamic() {
3482
+ return this;
3483
+ }
3484
+ }
3485
+
3486
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/count.js
3487
+ class SQLiteCountBuilder extends SQL {
3488
+ constructor(params) {
3489
+ super(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
3490
+ this.params = params;
3491
+ this.session = params.session;
3492
+ this.sql = SQLiteCountBuilder.buildCount(params.source, params.filters);
3493
+ }
3494
+ sql;
3495
+ static [entityKind] = "SQLiteCountBuilderAsync";
3496
+ [Symbol.toStringTag] = "SQLiteCountBuilderAsync";
3497
+ session;
3498
+ static buildEmbeddedCount(source, filters) {
3499
+ return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
3500
+ }
3501
+ static buildCount(source, filters) {
3502
+ return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
3503
+ }
3504
+ then(onfulfilled, onrejected) {
3505
+ return Promise.resolve(this.session.count(this.sql)).then(onfulfilled, onrejected);
3506
+ }
3507
+ catch(onRejected) {
3508
+ return this.then(undefined, onRejected);
3509
+ }
3510
+ finally(onFinally) {
3511
+ return this.then((value) => {
3512
+ onFinally?.();
3513
+ return value;
3514
+ }, (reason) => {
3515
+ onFinally?.();
3516
+ throw reason;
3517
+ });
3518
+ }
3519
+ }
3520
+
3521
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
3522
+ class RelationalQueryBuilder {
3523
+ constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) {
3524
+ this.mode = mode;
3525
+ this.fullSchema = fullSchema;
3526
+ this.schema = schema;
3527
+ this.tableNamesMap = tableNamesMap;
3528
+ this.table = table;
3529
+ this.tableConfig = tableConfig;
3530
+ this.dialect = dialect;
3531
+ this.session = session;
3532
+ }
3533
+ static [entityKind] = "SQLiteAsyncRelationalQueryBuilder";
3534
+ findMany(config) {
3535
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many");
3536
+ }
3537
+ findFirst(config) {
3538
+ return this.mode === "sync" ? new SQLiteSyncRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first") : new SQLiteRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first");
3539
+ }
3540
+ }
3541
+
3542
+ class SQLiteRelationalQuery extends QueryPromise {
3543
+ constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) {
3544
+ super();
3545
+ this.fullSchema = fullSchema;
3546
+ this.schema = schema;
3547
+ this.tableNamesMap = tableNamesMap;
3548
+ this.table = table;
3549
+ this.tableConfig = tableConfig;
3550
+ this.dialect = dialect;
3551
+ this.session = session;
3552
+ this.config = config;
3553
+ this.mode = mode;
3554
+ }
3555
+ static [entityKind] = "SQLiteAsyncRelationalQuery";
3556
+ mode;
3557
+ getSQL() {
3558
+ return this.dialect.buildRelationalQuery({
3559
+ fullSchema: this.fullSchema,
3560
+ schema: this.schema,
3561
+ tableNamesMap: this.tableNamesMap,
3562
+ table: this.table,
3563
+ tableConfig: this.tableConfig,
3564
+ queryConfig: this.config,
3565
+ tableAlias: this.tableConfig.tsName
3566
+ }).sql;
3567
+ }
3568
+ _prepare(isOneTimeQuery = false) {
3569
+ const { query, builtQuery } = this._toSQL();
3570
+ return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](builtQuery, undefined, this.mode === "first" ? "get" : "all", true, (rawRows, mapColumnValue) => {
3571
+ const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue));
3572
+ if (this.mode === "first") {
3573
+ return rows[0];
3574
+ }
3575
+ return rows;
3576
+ });
3577
+ }
3578
+ prepare() {
3579
+ return this._prepare(false);
3580
+ }
3581
+ _toSQL() {
3582
+ const query = this.dialect.buildRelationalQuery({
3583
+ fullSchema: this.fullSchema,
3584
+ schema: this.schema,
3585
+ tableNamesMap: this.tableNamesMap,
3586
+ table: this.table,
3587
+ tableConfig: this.tableConfig,
3588
+ queryConfig: this.config,
3589
+ tableAlias: this.tableConfig.tsName
3590
+ });
3591
+ const builtQuery = this.dialect.sqlToQuery(query.sql);
3592
+ return { query, builtQuery };
3593
+ }
3594
+ toSQL() {
3595
+ return this._toSQL().builtQuery;
3596
+ }
3597
+ executeRaw() {
3598
+ if (this.mode === "first") {
3599
+ return this._prepare(false).get();
3600
+ }
3601
+ return this._prepare(false).all();
3602
+ }
3603
+ async execute() {
3604
+ return this.executeRaw();
3605
+ }
3606
+ }
3607
+
3608
+ class SQLiteSyncRelationalQuery extends SQLiteRelationalQuery {
3609
+ static [entityKind] = "SQLiteSyncRelationalQuery";
3610
+ sync() {
3611
+ return this.executeRaw();
3612
+ }
3613
+ }
3614
+
3615
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
3616
+ class SQLiteRaw extends QueryPromise {
3617
+ constructor(execute, getSQL, action, dialect, mapBatchResult) {
3618
+ super();
3619
+ this.execute = execute;
3620
+ this.getSQL = getSQL;
3621
+ this.dialect = dialect;
3622
+ this.mapBatchResult = mapBatchResult;
3623
+ this.config = { action };
3624
+ }
3625
+ static [entityKind] = "SQLiteRaw";
3626
+ config;
3627
+ getQuery() {
3628
+ return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };
3629
+ }
3630
+ mapResult(result, isFromBatch) {
3631
+ return isFromBatch ? this.mapBatchResult(result) : result;
3632
+ }
3633
+ _prepare() {
3634
+ return this;
3635
+ }
3636
+ isResponseInArrayMode() {
3637
+ return false;
3638
+ }
3639
+ }
3640
+
3641
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/db.js
3642
+ class BaseSQLiteDatabase {
3643
+ constructor(resultKind, dialect, session, schema) {
3644
+ this.resultKind = resultKind;
3645
+ this.dialect = dialect;
3646
+ this.session = session;
3647
+ this._ = schema ? {
3648
+ schema: schema.schema,
3649
+ fullSchema: schema.fullSchema,
3650
+ tableNamesMap: schema.tableNamesMap
3651
+ } : {
3652
+ schema: undefined,
3653
+ fullSchema: {},
3654
+ tableNamesMap: {}
3655
+ };
3656
+ this.query = {};
3657
+ const query = this.query;
3658
+ if (this._.schema) {
3659
+ for (const [tableName, columns] of Object.entries(this._.schema)) {
3660
+ query[tableName] = new RelationalQueryBuilder(resultKind, schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session);
3661
+ }
3662
+ }
3663
+ }
3664
+ static [entityKind] = "BaseSQLiteDatabase";
3665
+ query;
3666
+ $with(alias) {
3667
+ const self = this;
3668
+ return {
3669
+ as(qb) {
3670
+ if (typeof qb === "function") {
3671
+ qb = qb(new QueryBuilder(self.dialect));
3672
+ }
3673
+ return new Proxy(new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }));
3674
+ }
3675
+ };
3676
+ }
3677
+ $count(source, filters) {
3678
+ return new SQLiteCountBuilder({ source, filters, session: this.session });
3679
+ }
3680
+ with(...queries) {
3681
+ const self = this;
3682
+ function select(fields) {
3683
+ return new SQLiteSelectBuilder({
3684
+ fields: fields ?? undefined,
3685
+ session: self.session,
3686
+ dialect: self.dialect,
3687
+ withList: queries
3688
+ });
3689
+ }
3690
+ function selectDistinct(fields) {
3691
+ return new SQLiteSelectBuilder({
3692
+ fields: fields ?? undefined,
3693
+ session: self.session,
3694
+ dialect: self.dialect,
3695
+ withList: queries,
3696
+ distinct: true
3697
+ });
3698
+ }
3699
+ function update(table) {
3700
+ return new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);
3701
+ }
3702
+ function insert(into) {
3703
+ return new SQLiteInsertBuilder(into, self.session, self.dialect, queries);
3704
+ }
3705
+ function delete_(from) {
3706
+ return new SQLiteDeleteBase(from, self.session, self.dialect, queries);
3707
+ }
3708
+ return { select, selectDistinct, update, insert, delete: delete_ };
3709
+ }
3710
+ select(fields) {
3711
+ return new SQLiteSelectBuilder({ fields: fields ?? undefined, session: this.session, dialect: this.dialect });
3712
+ }
3713
+ selectDistinct(fields) {
3714
+ return new SQLiteSelectBuilder({
3715
+ fields: fields ?? undefined,
3716
+ session: this.session,
3717
+ dialect: this.dialect,
3718
+ distinct: true
3719
+ });
3720
+ }
3721
+ update(table) {
3722
+ return new SQLiteUpdateBuilder(table, this.session, this.dialect);
3723
+ }
3724
+ insert(into) {
3725
+ return new SQLiteInsertBuilder(into, this.session, this.dialect);
3726
+ }
3727
+ delete(from) {
3728
+ return new SQLiteDeleteBase(from, this.session, this.dialect);
3729
+ }
3730
+ run(query) {
3731
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3732
+ if (this.resultKind === "async") {
3733
+ return new SQLiteRaw(async () => this.session.run(sequel), () => sequel, "run", this.dialect, this.session.extractRawRunValueFromBatchResult.bind(this.session));
3734
+ }
3735
+ return this.session.run(sequel);
3736
+ }
3737
+ all(query) {
3738
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3739
+ if (this.resultKind === "async") {
3740
+ return new SQLiteRaw(async () => this.session.all(sequel), () => sequel, "all", this.dialect, this.session.extractRawAllValueFromBatchResult.bind(this.session));
3741
+ }
3742
+ return this.session.all(sequel);
3743
+ }
3744
+ get(query) {
3745
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3746
+ if (this.resultKind === "async") {
3747
+ return new SQLiteRaw(async () => this.session.get(sequel), () => sequel, "get", this.dialect, this.session.extractRawGetValueFromBatchResult.bind(this.session));
3748
+ }
3749
+ return this.session.get(sequel);
3750
+ }
3751
+ values(query) {
3752
+ const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
3753
+ if (this.resultKind === "async") {
3754
+ return new SQLiteRaw(async () => this.session.values(sequel), () => sequel, "values", this.dialect, this.session.extractRawValuesValueFromBatchResult.bind(this.session));
3755
+ }
3756
+ return this.session.values(sequel);
3757
+ }
3758
+ transaction(transaction, config) {
3759
+ return this.session.transaction(transaction, config);
3760
+ }
3761
+ }
3762
+
3763
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/sqlite-core/session.js
3764
+ class ExecuteResultSync extends QueryPromise {
3765
+ constructor(resultCb) {
3766
+ super();
3767
+ this.resultCb = resultCb;
3768
+ }
3769
+ static [entityKind] = "ExecuteResultSync";
3770
+ async execute() {
3771
+ return this.resultCb();
3772
+ }
3773
+ sync() {
3774
+ return this.resultCb();
3775
+ }
3776
+ }
3777
+
3778
+ class SQLitePreparedQuery {
3779
+ constructor(mode, executeMethod, query) {
3780
+ this.mode = mode;
3781
+ this.executeMethod = executeMethod;
3782
+ this.query = query;
3783
+ }
3784
+ static [entityKind] = "PreparedQuery";
3785
+ joinsNotNullableMap;
3786
+ getQuery() {
3787
+ return this.query;
3788
+ }
3789
+ mapRunResult(result, _isFromBatch) {
3790
+ return result;
3791
+ }
3792
+ mapAllResult(_result, _isFromBatch) {
3793
+ throw new Error("Not implemented");
3794
+ }
3795
+ mapGetResult(_result, _isFromBatch) {
3796
+ throw new Error("Not implemented");
3797
+ }
3798
+ execute(placeholderValues) {
3799
+ if (this.mode === "async") {
3800
+ return this[this.executeMethod](placeholderValues);
3801
+ }
3802
+ return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
3803
+ }
3804
+ mapResult(response, isFromBatch) {
3805
+ switch (this.executeMethod) {
3806
+ case "run": {
3807
+ return this.mapRunResult(response, isFromBatch);
3808
+ }
3809
+ case "all": {
3810
+ return this.mapAllResult(response, isFromBatch);
3811
+ }
3812
+ case "get": {
3813
+ return this.mapGetResult(response, isFromBatch);
3814
+ }
3815
+ }
3816
+ }
3817
+ }
3818
+
3819
+ class SQLiteSession {
3820
+ constructor(dialect) {
3821
+ this.dialect = dialect;
3822
+ }
3823
+ static [entityKind] = "SQLiteSession";
3824
+ prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode) {
3825
+ return this.prepareQuery(query, fields, executeMethod, isResponseInArrayMode);
3826
+ }
3827
+ run(query) {
3828
+ const staticQuery = this.dialect.sqlToQuery(query);
3829
+ try {
3830
+ return this.prepareOneTimeQuery(staticQuery, undefined, "run", false).run();
3831
+ } catch (err) {
3832
+ throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });
3833
+ }
3834
+ }
3835
+ extractRawRunValueFromBatchResult(result) {
3836
+ return result;
3837
+ }
3838
+ all(query) {
3839
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).all();
3840
+ }
3841
+ extractRawAllValueFromBatchResult(_result) {
3842
+ throw new Error("Not implemented");
3843
+ }
3844
+ get(query) {
3845
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).get();
3846
+ }
3847
+ extractRawGetValueFromBatchResult(_result) {
3848
+ throw new Error("Not implemented");
3849
+ }
3850
+ values(query) {
3851
+ return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, "run", false).values();
3852
+ }
3853
+ async count(sql2) {
3854
+ const result = await this.values(sql2);
3855
+ return result[0][0];
3856
+ }
3857
+ extractRawValuesValueFromBatchResult(_result) {
3858
+ throw new Error("Not implemented");
3859
+ }
3860
+ }
3861
+
3862
+ class SQLiteTransaction extends BaseSQLiteDatabase {
3863
+ constructor(resultType, dialect, session, schema, nestedIndex = 0) {
3864
+ super(resultType, dialect, session, schema);
3865
+ this.schema = schema;
3866
+ this.nestedIndex = nestedIndex;
3867
+ }
3868
+ static [entityKind] = "SQLiteTransaction";
3869
+ rollback() {
3870
+ throw new TransactionRollbackError;
3871
+ }
3872
+ }
3873
+
3874
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/bun-sqlite/session.js
3875
+ class SQLiteBunSession extends SQLiteSession {
3876
+ constructor(client, dialect, schema, options = {}) {
3877
+ super(dialect);
3878
+ this.client = client;
3879
+ this.schema = schema;
3880
+ this.logger = options.logger ?? new NoopLogger;
3881
+ }
3882
+ static [entityKind] = "SQLiteBunSession";
3883
+ logger;
3884
+ exec(query) {
3885
+ this.client.exec(query);
3886
+ }
3887
+ prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper) {
3888
+ const stmt = this.client.prepare(query.sql);
3889
+ return new PreparedQuery(stmt, query, this.logger, fields, executeMethod, isResponseInArrayMode, customResultMapper);
3890
+ }
3891
+ transaction(transaction, config = {}) {
3892
+ const tx = new SQLiteBunTransaction("sync", this.dialect, this, this.schema);
3893
+ let result;
3894
+ const nativeTx = this.client.transaction(() => {
3895
+ result = transaction(tx);
3896
+ });
3897
+ nativeTx[config.behavior ?? "deferred"]();
3898
+ return result;
3899
+ }
3900
+ }
3901
+
3902
+ class SQLiteBunTransaction extends SQLiteTransaction {
3903
+ static [entityKind] = "SQLiteBunTransaction";
3904
+ transaction(transaction) {
3905
+ const savepointName = `sp${this.nestedIndex}`;
3906
+ const tx = new SQLiteBunTransaction("sync", this.dialect, this.session, this.schema, this.nestedIndex + 1);
3907
+ this.session.run(sql.raw(`savepoint ${savepointName}`));
3908
+ try {
3909
+ const result = transaction(tx);
3910
+ this.session.run(sql.raw(`release savepoint ${savepointName}`));
3911
+ return result;
3912
+ } catch (err) {
3913
+ this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
3914
+ throw err;
3915
+ }
3916
+ }
3917
+ }
3918
+
3919
+ class PreparedQuery extends SQLitePreparedQuery {
3920
+ constructor(stmt, query, logger, fields, executeMethod, _isResponseInArrayMode, customResultMapper) {
3921
+ super("sync", executeMethod, query);
3922
+ this.stmt = stmt;
3923
+ this.logger = logger;
3924
+ this.fields = fields;
3925
+ this._isResponseInArrayMode = _isResponseInArrayMode;
3926
+ this.customResultMapper = customResultMapper;
3927
+ }
3928
+ static [entityKind] = "SQLiteBunPreparedQuery";
3929
+ run(placeholderValues) {
3930
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
3931
+ this.logger.logQuery(this.query.sql, params);
3932
+ return this.stmt.run(...params);
3933
+ }
3934
+ all(placeholderValues) {
3935
+ const { fields, query, logger, joinsNotNullableMap, stmt, customResultMapper } = this;
3936
+ if (!fields && !customResultMapper) {
3937
+ const params = fillPlaceholders(query.params, placeholderValues ?? {});
3938
+ logger.logQuery(query.sql, params);
3939
+ return stmt.all(...params);
3940
+ }
3941
+ const rows = this.values(placeholderValues);
3942
+ if (customResultMapper) {
3943
+ return customResultMapper(rows);
3944
+ }
3945
+ return rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap));
3946
+ }
3947
+ get(placeholderValues) {
3948
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
3949
+ this.logger.logQuery(this.query.sql, params);
3950
+ const row = this.stmt.values(...params)[0];
3951
+ if (!row) {
3952
+ return;
3953
+ }
3954
+ const { fields, joinsNotNullableMap, customResultMapper } = this;
3955
+ if (!fields && !customResultMapper) {
3956
+ return row;
3957
+ }
3958
+ if (customResultMapper) {
3959
+ return customResultMapper([row]);
3960
+ }
3961
+ return mapResultRow(fields, row, joinsNotNullableMap);
3962
+ }
3963
+ values(placeholderValues) {
3964
+ const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
3965
+ this.logger.logQuery(this.query.sql, params);
3966
+ return this.stmt.values(...params);
3967
+ }
3968
+ isResponseInArrayMode() {
3969
+ return this._isResponseInArrayMode;
3970
+ }
3971
+ }
3972
+
3973
+ // ../../node_modules/.bun/drizzle-orm@0.38.4+11aa72c9bfcf30b8/node_modules/drizzle-orm/bun-sqlite/driver.js
3974
+ class BunSQLiteDatabase extends BaseSQLiteDatabase {
3975
+ static [entityKind] = "BunSQLiteDatabase";
3976
+ }
3977
+ function construct(client, config = {}) {
3978
+ const dialect = new SQLiteSyncDialect({ casing: config.casing });
3979
+ let logger;
3980
+ if (config.logger === true) {
3981
+ logger = new DefaultLogger;
3982
+ } else if (config.logger !== false) {
3983
+ logger = config.logger;
3984
+ }
3985
+ let schema;
3986
+ if (config.schema) {
3987
+ const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers);
3988
+ schema = {
3989
+ fullSchema: config.schema,
3990
+ schema: tablesConfig.tables,
3991
+ tableNamesMap: tablesConfig.tableNamesMap
3992
+ };
3993
+ }
3994
+ const session = new SQLiteBunSession(client, dialect, schema, { logger });
3995
+ const db = new BunSQLiteDatabase("sync", dialect, session, schema);
3996
+ db.$client = client;
3997
+ return db;
3998
+ }
3999
+ function drizzle(...params) {
4000
+ if (params[0] === undefined || typeof params[0] === "string") {
4001
+ const instance = params[0] === undefined ? new Database : new Database(params[0]);
4002
+ return construct(instance, params[1]);
4003
+ }
4004
+ if (isConfig(params[0])) {
4005
+ const { connection, client, ...drizzleConfig } = params[0];
4006
+ if (client)
4007
+ return construct(client, drizzleConfig);
4008
+ if (typeof connection === "object") {
4009
+ const { source, ...opts } = connection;
4010
+ const options = Object.values(opts).filter((v3) => v3 !== undefined).length ? opts : undefined;
4011
+ const instance2 = new Database(source, options);
4012
+ return construct(instance2, drizzleConfig);
4013
+ }
4014
+ const instance = new Database(connection);
4015
+ return construct(instance, drizzleConfig);
4016
+ }
4017
+ return construct(params[0], params[1]);
4018
+ }
4019
+ ((drizzle2) => {
4020
+ function mock(config) {
4021
+ return construct({}, config);
4022
+ }
4023
+ drizzle2.mock = mock;
4024
+ })(drizzle || (drizzle = {}));
4025
+
4026
+ // lib/db.ts
4027
+ import path from "path";
4028
+ import os from "os";
4029
+ import fs from "fs";
4030
+ var wallets = sqliteTable("wallets", {
4031
+ id: text("id").primaryKey(),
4032
+ name: text("name").notNull(),
4033
+ balance: real("balance").notNull().default(0),
4034
+ initial_balance: real("initial_balance").notNull().default(0),
4035
+ currency: text("currency").notNull().default("USD"),
4036
+ updated_at: text("updated_at").notNull(),
4037
+ created_at: text("created_at").notNull()
4038
+ });
4039
+ var transactions = sqliteTable("transactions", {
4040
+ id: text("id").primaryKey(),
4041
+ provider: text("provider").notNull(),
4042
+ model: text("model").notNull(),
4043
+ cost: real("cost").notNull(),
4044
+ input_tokens: integer("input_tokens"),
4045
+ output_tokens: integer("output_tokens"),
4046
+ session_id: text("session_id"),
4047
+ created_at: text("created_at").notNull(),
4048
+ synced: integer("synced").default(0)
4049
+ });
4050
+ var dbPath = path.join(os.homedir(), ".config", "opencode", "ai-ledger", "wallet.db");
4051
+ var dbInstance = null;
4052
+ function getDb() {
4053
+ if (!dbInstance) {
4054
+ const dbDir = path.dirname(dbPath);
4055
+ if (!fs.existsSync(dbDir)) {
4056
+ fs.mkdirSync(dbDir, { recursive: true });
4057
+ }
4058
+ const sqliteDb = new Database2(dbPath);
4059
+ dbInstance = drizzle(sqliteDb);
4060
+ }
4061
+ return dbInstance;
4062
+ }
4063
+ async function initializeDatabase() {
4064
+ const db = getDb();
4065
+ db.run(sql`
4066
+ CREATE TABLE IF NOT EXISTS wallets (
4067
+ id TEXT PRIMARY KEY,
4068
+ name TEXT NOT NULL,
4069
+ balance REAL NOT NULL DEFAULT 0,
4070
+ initial_balance REAL NOT NULL DEFAULT 0,
4071
+ currency TEXT NOT NULL DEFAULT 'USD',
4072
+ updated_at TEXT NOT NULL,
4073
+ created_at TEXT NOT NULL
4074
+ )
4075
+ `);
4076
+ db.run(sql`
4077
+ CREATE TABLE IF NOT EXISTS transactions (
4078
+ id TEXT PRIMARY KEY,
4079
+ provider TEXT NOT NULL,
4080
+ model TEXT NOT NULL,
4081
+ cost REAL NOT NULL,
4082
+ input_tokens INTEGER,
4083
+ output_tokens INTEGER,
4084
+ session_id TEXT,
4085
+ created_at TEXT NOT NULL,
4086
+ synced INTEGER DEFAULT 0
4087
+ )
4088
+ `);
4089
+ }
4090
+ async function getWallet(provider) {
4091
+ const db = getDb();
4092
+ const result = await db.select().from(wallets).where(eq(wallets.id, provider)).limit(1);
4093
+ return result[0] || null;
4094
+ }
4095
+ async function getAllWallets() {
4096
+ const db = getDb();
4097
+ return await db.select().from(wallets).orderBy(wallets.name);
4098
+ }
4099
+ async function upsertWallet(data) {
4100
+ const db = getDb();
4101
+ const now = new Date().toISOString();
4102
+ db.run(sql`
4103
+ INSERT INTO wallets (id, name, balance, initial_balance, currency, updated_at, created_at)
4104
+ VALUES (${data.id}, ${data.name}, 0, 0, ${data.currency}, ${now}, ${now})
4105
+ ON CONFLICT(id) DO NOTHING
4106
+ `);
4107
+ }
4108
+ async function addBalance(id, amount) {
4109
+ const wallet = await getWallet(id);
4110
+ if (!wallet)
4111
+ throw new Error(`Wallet '${id}' not found`);
4112
+ const newBalance = wallet.balance + amount;
4113
+ const newInitial = wallet.initial_balance + amount;
4114
+ const now = new Date().toISOString();
4115
+ const db = getDb();
4116
+ await db.update(wallets).set({ balance: newBalance, initial_balance: newInitial, updated_at: now }).where(eq(wallets.id, id));
4117
+ return newBalance;
4118
+ }
4119
+ async function setWalletBalance(id, amount) {
4120
+ const db = getDb();
4121
+ const now = new Date().toISOString();
4122
+ await db.update(wallets).set({
4123
+ balance: amount,
4124
+ initial_balance: amount,
4125
+ updated_at: now
4126
+ }).where(eq(wallets.id, id));
4127
+ }
4128
+ async function getAllTransactions(limit = 50) {
4129
+ const db = getDb();
4130
+ return await db.select().from(transactions).orderBy(desc(transactions.created_at)).limit(limit);
4131
+ }
4132
+
4133
+ // lib/format.ts
4134
+ function formatCurrency(amount) {
4135
+ const sign = amount < 0 ? "-" : "";
4136
+ return `${sign}$${Math.abs(amount).toFixed(2)}`;
4137
+ }
4138
+ function formatProgressBar(spent, initial) {
4139
+ if (initial === 0)
4140
+ return "\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591";
4141
+ const percentage = spent / initial * 100;
4142
+ const filledCount = Math.min(20, Math.max(0, Math.round(percentage / 100 * 20)));
4143
+ const emptyCount = 20 - filledCount;
4144
+ return "\u2588".repeat(filledCount) + "\u2591".repeat(emptyCount);
4145
+ }
4146
+ function formatBalanceTable(wallets2) {
4147
+ if (wallets2.length === 0) {
4148
+ return "No wallets configured. Run: ai-ledger setup";
4149
+ }
4150
+ const header = ["Provider", "Balance", "Spent", "Progress"];
4151
+ const rows = [];
4152
+ for (const wallet of wallets2) {
4153
+ const spent = wallet.initial_balance - wallet.balance;
4154
+ const progressBar = formatProgressBar(spent, wallet.initial_balance);
4155
+ rows.push([
4156
+ wallet.name,
4157
+ formatCurrency(wallet.balance),
4158
+ formatCurrency(spent),
4159
+ progressBar
4160
+ ]);
4161
+ }
4162
+ const colWidths = header.map((h, i) => {
4163
+ const maxContentWidth = Math.max(h.length, ...rows.map((row) => row[i]?.length || 0));
4164
+ return maxContentWidth + 2;
4165
+ });
4166
+ let table = "\u250C";
4167
+ for (let i = 0;i < header.length; i++) {
4168
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4169
+ if (i < header.length - 1)
4170
+ table += "\u252C";
4171
+ }
4172
+ table += `\u2510
4173
+ `;
4174
+ table += "\u2502";
4175
+ for (let i = 0;i < header.length; i++) {
4176
+ const padding = " ".repeat(Math.floor(((colWidths[i] ?? 0) - (header[i]?.length || 0)) / 2));
4177
+ table += padding + (header[i] || "") + padding;
4178
+ if ((colWidths[i] ?? 0) - (header[i]?.length || 0) - padding.length * 2 > 0) {
4179
+ table += " ";
4180
+ }
4181
+ table += "\u2502";
4182
+ }
4183
+ table += `
4184
+ `;
4185
+ table += "\u251C";
4186
+ for (let i = 0;i < header.length; i++) {
4187
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4188
+ if (i < header.length - 1)
4189
+ table += "\u253C";
4190
+ }
4191
+ table += `\u2524
4192
+ `;
4193
+ for (const row of rows) {
4194
+ table += "\u2502";
4195
+ for (let i = 0;i < row.length; i++) {
4196
+ const cell = row[i] || "";
4197
+ table += " " + cell.padEnd((colWidths[i] ?? 0) - 1);
4198
+ table += "\u2502";
4199
+ }
4200
+ table += `
4201
+ `;
4202
+ }
4203
+ table += "\u2514";
4204
+ for (let i = 0;i < header.length; i++) {
4205
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4206
+ if (i < header.length - 1)
4207
+ table += "\u2534";
4208
+ }
4209
+ table += "\u2518";
4210
+ return table;
4211
+ }
4212
+ function formatTransactionHistory(txs) {
4213
+ if (txs.length === 0) {
4214
+ return "No transactions recorded yet.";
4215
+ }
4216
+ const header = ["Date", "Provider", "Model", "Cost", "Tokens In", "Tokens Out"];
4217
+ const rows = txs.map((tx) => [
4218
+ new Date(tx.created_at).toLocaleString(),
4219
+ tx.provider,
4220
+ tx.model,
4221
+ formatCurrency(tx.cost),
4222
+ tx.input_tokens?.toString() ?? "-",
4223
+ tx.output_tokens?.toString() ?? "-"
4224
+ ]);
4225
+ const colWidths = header.map((h, i) => {
4226
+ const maxContentWidth = Math.max(h.length, ...rows.map((row) => row[i]?.length || 0));
4227
+ return maxContentWidth + 2;
4228
+ });
4229
+ let table = "\u250C";
4230
+ for (let i = 0;i < header.length; i++) {
4231
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4232
+ if (i < header.length - 1)
4233
+ table += "\u252C";
4234
+ }
4235
+ table += `\u2510
4236
+ `;
4237
+ table += "\u2502";
4238
+ for (let i = 0;i < header.length; i++) {
4239
+ const padding = " ".repeat(Math.floor(((colWidths[i] ?? 0) - (header[i]?.length || 0)) / 2));
4240
+ table += padding + (header[i] || "") + padding;
4241
+ if ((colWidths[i] ?? 0) - (header[i]?.length || 0) - padding.length * 2 > 0) {
4242
+ table += " ";
4243
+ }
4244
+ table += "\u2502";
4245
+ }
4246
+ table += `
4247
+ `;
4248
+ table += "\u251C";
4249
+ for (let i = 0;i < header.length; i++) {
4250
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4251
+ if (i < header.length - 1)
4252
+ table += "\u253C";
4253
+ }
4254
+ table += `\u2524
4255
+ `;
4256
+ for (const row of rows) {
4257
+ table += "\u2502";
4258
+ for (let i = 0;i < row.length; i++) {
4259
+ const cell = row[i] || "";
4260
+ table += " " + cell.padEnd((colWidths[i] ?? 0) - 1);
4261
+ table += "\u2502";
4262
+ }
4263
+ table += `
4264
+ `;
4265
+ }
4266
+ table += "\u2514";
4267
+ for (let i = 0;i < header.length; i++) {
4268
+ table += "\u2500".repeat(colWidths[i] ?? 0);
4269
+ if (i < header.length - 1)
4270
+ table += "\u2534";
4271
+ }
4272
+ table += "\u2518";
4273
+ return table;
4274
+ }
4275
+
4276
+ // lib/providers.ts
4277
+ var PROVIDER_ENV = {
4278
+ openai: { envVar: "OPENAI_API_KEY", name: "OpenAI", currency: "USD" },
4279
+ anthropic: {
4280
+ envVar: "ANTHROPIC_API_KEY",
4281
+ name: "Anthropic",
4282
+ currency: "USD"
4283
+ },
4284
+ kimi: { envVar: "MOONSHOT_API_KEY", name: "Kimi", currency: "USD" },
4285
+ minimax: { envVar: "MINIMAX_API_KEY", name: "MiniMax", currency: "USD" }
4286
+ };
4287
+ function detectProviders() {
4288
+ return Object.entries(PROVIDER_ENV).filter(([_, { envVar }]) => !!process.env[envVar]).map(([id]) => id);
4289
+ }
4290
+ function getProviderName(providerId) {
4291
+ return PROVIDER_ENV[providerId]?.name || providerId;
4292
+ }
4293
+ function getProviderCurrency(providerId) {
4294
+ return PROVIDER_ENV[providerId]?.currency || "USD";
4295
+ }
4296
+
4297
+ // cli.ts
4298
+ function expandHome(p2) {
4299
+ if (p2.startsWith("~"))
4300
+ return path2.join(os2.homedir(), p2.slice(1));
4301
+ return p2;
4302
+ }
4303
+ async function detectProvidersFromOpenCode() {
4304
+ try {
4305
+ const res = await fetch("http://127.0.0.1:4096/provider", {
4306
+ signal: AbortSignal.timeout(500)
4307
+ });
4308
+ if (res.ok) {
4309
+ const data = await res.json();
4310
+ const ids = data.filter((p2) => p2.source === "env" || p2.source === "config").map((p2) => p2.id);
4311
+ if (ids.length > 0)
4312
+ return ids;
4313
+ }
4314
+ } catch {}
4315
+ return detectProviders();
4316
+ }
4317
+ function getProviderInfo(id) {
4318
+ return {
4319
+ name: getProviderName(id),
4320
+ currency: getProviderCurrency(id)
4321
+ };
4322
+ }
4323
+ async function cmdSetup() {
4324
+ we("ai-ledger setup");
4325
+ const s = L2();
4326
+ s.start("Detecting AI providers\u2026");
4327
+ let providers;
4328
+ try {
4329
+ providers = await detectProvidersFromOpenCode();
4330
+ } catch {
4331
+ providers = detectProviders();
4332
+ }
4333
+ s.stop(providers.length > 0 ? `Found ${providers.length} provider(s): ${providers.join(", ")}` : "No providers detected");
4334
+ if (providers.length === 0) {
4335
+ v2.warn("Set at least one API key (OPENAI_API_KEY, ANTHROPIC_API_KEY, \u2026) and re-run setup.");
4336
+ fe("Setup incomplete");
4337
+ return;
4338
+ }
4339
+ await initializeDatabase();
4340
+ s.start("Creating wallets\u2026");
4341
+ for (const id of providers) {
4342
+ const { name, currency } = getProviderInfo(id);
4343
+ await upsertWallet({ id, name, currency });
4344
+ }
4345
+ s.stop("Wallets ready");
4346
+ const configPath = expandHome("~/.config/opencode/opencode.json");
4347
+ if (fs2.existsSync(configPath)) {
4348
+ s.start("Registering plugin in opencode.json\u2026");
4349
+ try {
4350
+ const config = JSON.parse(fs2.readFileSync(configPath, "utf8"));
4351
+ const existing = config.plugin ?? [];
4352
+ config.plugin = [...new Set([...existing, "@kapishdima/ai-ledger"])];
4353
+ fs2.writeFileSync(configPath, JSON.stringify(config, null, 2));
4354
+ s.stop("Plugin registered in opencode.json");
4355
+ } catch (err) {
4356
+ s.stop(`Could not update opencode.json: ${err.message}`);
4357
+ }
4358
+ } else {
4359
+ v2.warn(`opencode.json not found at ${configPath}. Add "@kapishdima/ai-ledger" to the plugin array manually.`);
4360
+ }
4361
+ v2.info(`Set initial balances with: ai-ledger set <provider> <amount>`);
4362
+ fe("Setup complete!");
4363
+ }
4364
+ async function cmdBalance() {
4365
+ await initializeDatabase();
4366
+ const wallets2 = await getAllWallets();
4367
+ console.log(formatBalanceTable(wallets2));
4368
+ }
4369
+ async function cmdSet(provider, amount) {
4370
+ if (!provider) {
4371
+ console.error("Usage: ai-ledger set <provider> <amount>");
4372
+ process.exit(1);
4373
+ }
4374
+ if (isNaN(amount) || amount < 0) {
4375
+ console.error("Amount must be a non-negative number");
4376
+ process.exit(1);
4377
+ }
4378
+ await initializeDatabase();
4379
+ const existing = await getWallet(provider);
4380
+ if (!existing) {
4381
+ const { name, currency } = getProviderInfo(provider);
4382
+ await upsertWallet({ id: provider, name, currency });
4383
+ }
4384
+ await setWalletBalance(provider, amount);
4385
+ console.log(`${getProviderName(provider)}: balance set to ${formatCurrency(amount)}`);
4386
+ }
4387
+ async function cmdAdd(provider, amount) {
4388
+ if (!provider) {
4389
+ console.error("Usage: ai-ledger add <provider> <amount>");
4390
+ process.exit(1);
4391
+ }
4392
+ if (isNaN(amount) || amount <= 0) {
4393
+ console.error("Amount must be a positive number");
4394
+ process.exit(1);
4395
+ }
4396
+ await initializeDatabase();
4397
+ const wallet = await getWallet(provider);
4398
+ if (!wallet) {
4399
+ const { name, currency } = getProviderInfo(provider);
4400
+ await upsertWallet({ id: provider, name, currency });
4401
+ await setWalletBalance(provider, amount);
4402
+ console.log(`${getProviderName(provider)}: created with balance ${formatCurrency(amount)}`);
4403
+ } else {
4404
+ const newBalance = await addBalance(provider, amount);
4405
+ console.log(`${getProviderName(provider)}: ${formatCurrency(amount)} added \u2192 ${formatCurrency(newBalance)}`);
4406
+ }
4407
+ }
4408
+ async function cmdHistory(limit = 50) {
4409
+ await initializeDatabase();
4410
+ const txs = await getAllTransactions(limit);
4411
+ console.log(formatTransactionHistory(txs));
4412
+ }
4413
+ function cmdHelp() {
4414
+ console.log(`
4415
+ ai-ledger \u2014 AI provider balance tracker for OpenCode
4416
+
4417
+ Commands:
4418
+ setup Detect providers, create wallets, register plugin
4419
+ balance Show current balances with progress bars
4420
+ set <provider> <amt> Set (reset) wallet balance
4421
+ add <provider> <amt> Add funds to a wallet
4422
+ history [limit] Show recent transactions (default: 50)
4423
+ help Show this help
4424
+
4425
+ Examples:
4426
+ ai-ledger setup
4427
+ ai-ledger balance
4428
+ ai-ledger set anthropic 20
4429
+ ai-ledger add openai 10
4430
+ ai-ledger history 20
4431
+ `.trim());
4432
+ }
4433
+ var args = process.argv.slice(2);
4434
+ var cmd = args[0];
4435
+ switch (cmd) {
4436
+ case "setup":
4437
+ await cmdSetup();
4438
+ break;
4439
+ case "balance":
4440
+ case undefined:
4441
+ await cmdBalance();
4442
+ break;
4443
+ case "set":
4444
+ await cmdSet(args[1] ?? "", parseFloat(args[2] ?? ""));
4445
+ break;
4446
+ case "add":
4447
+ await cmdAdd(args[1] ?? "", parseFloat(args[2] ?? ""));
4448
+ break;
4449
+ case "history":
4450
+ await cmdHistory(args[1] ? parseInt(args[1]) : 50);
4451
+ break;
4452
+ case "--help":
4453
+ case "-h":
4454
+ case "help":
4455
+ cmdHelp();
4456
+ break;
4457
+ default:
4458
+ console.error(`Unknown command: ${cmd}`);
4459
+ cmdHelp();
4460
+ process.exit(1);
4461
+ }