@hot-updater/postgres 0.36.6 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,1154 +1,274 @@
1
- import { createRequire } from "node:module";
2
- import { NIL_UUID, getAssetBaseStorageUri, getBundlePatches, getManifestFileHash, getManifestStorageUri, stripBundleArtifactMetadata } from "@hot-updater/core";
3
- import { calculatePagination, createDatabasePlugin } from "@hot-updater/plugin-core";
4
- import { Kysely, PostgresDialect } from "kysely";
5
- import { Pool } from "pg";
6
- //#region \0rolldown/runtime.js
7
- var __create = Object.create;
8
- var __defProp = Object.defineProperty;
9
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
- var __getOwnPropNames = Object.getOwnPropertyNames;
11
- var __getProtoOf = Object.getPrototypeOf;
12
- var __hasOwnProp = Object.prototype.hasOwnProperty;
13
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
16
- key = keys[i];
17
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
18
- get: ((k) => from[k]).bind(null, key),
19
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
- });
21
- }
22
- return to;
1
+ import { createDatabasePlugin } from "@hot-updater/plugin-core";
2
+ import { DatabaseRowReferencedError, createDatabasePluginAdapter } from "@hot-updater/plugin-core/internal";
3
+ import { Kysely, PostgresDialect, sql } from "kysely";
4
+ import pg from "pg";
5
+ //#region src/postgresQuery.ts
6
+ const applyOrder = (order, clause) => {
7
+ const directed = clause.direction === "asc" ? order.asc() : order.desc();
8
+ return clause.nulls === void 0 ? directed : clause.nulls === "first" ? directed.nullsFirst() : directed.nullsLast();
23
9
  };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
25
- value: mod,
26
- enumerable: true
27
- }) : target, mod));
28
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
29
- //#endregion
30
- //#region ../js/dist/index.mjs
31
- const LETTER_DASH_NUMBER = "[a-zA-Z0-9-]";
32
- const NUMERIC_IDENTIFIER = String.raw`0|[1-9]\d*`;
33
- const NUMERIC_IDENTIFIER_LOOSE = String.raw`\d+`;
34
- const NON_NUMERIC_IDENTIFIER = String.raw`\d*[a-zA-Z-]${LETTER_DASH_NUMBER}*`;
35
- const MAIN_VERSION = String.raw`(${NUMERIC_IDENTIFIER})\.(${NUMERIC_IDENTIFIER})\.(${NUMERIC_IDENTIFIER})`;
36
- const MAIN_VERSION_LOOSE = String.raw`(${NUMERIC_IDENTIFIER_LOOSE})\.(${NUMERIC_IDENTIFIER_LOOSE})\.(${NUMERIC_IDENTIFIER_LOOSE})`;
37
- const PRERELEASE_IDENTIFIER = `(?:${NON_NUMERIC_IDENTIFIER}|${NUMERIC_IDENTIFIER})`;
38
- const PRERELEASE_IDENTIFIER_LOOSE = `(?:${NON_NUMERIC_IDENTIFIER}|${NUMERIC_IDENTIFIER_LOOSE})`;
39
- const PRERELEASE = String.raw`(?:-(${PRERELEASE_IDENTIFIER}(?:\.${PRERELEASE_IDENTIFIER})*))`;
40
- const PRERELEASE_LOOSE = String.raw`(?:-?(${PRERELEASE_IDENTIFIER_LOOSE}(?:\.${PRERELEASE_IDENTIFIER_LOOSE})*))`;
41
- const BUILD_IDENTIFIER = `${LETTER_DASH_NUMBER}+`;
42
- const BUILD = String.raw`(?:\+(${BUILD_IDENTIFIER}(?:\.${BUILD_IDENTIFIER})*))`;
43
- const FULL_PLAIN = `v?${MAIN_VERSION}${PRERELEASE}?${BUILD}?`;
44
- const LOOSE_PLAIN = String.raw`[v=\s]*${MAIN_VERSION_LOOSE}${PRERELEASE_LOOSE}?${BUILD}?`;
45
- const GREATER_LESS_THAN = "((?:<|>)?=?)";
46
- const XRANGE_IDENTIFIER = String.raw`${NUMERIC_IDENTIFIER}|x|X|\*`;
47
- const XRANGE_IDENTIFIER_LOOSE = String.raw`${NUMERIC_IDENTIFIER_LOOSE}|x|X|\*`;
48
- const XRANGE_PLAIN = String.raw`[v=\s]*(${XRANGE_IDENTIFIER})(?:\.(${XRANGE_IDENTIFIER})(?:\.(${XRANGE_IDENTIFIER})(?:${PRERELEASE})?${BUILD}?)?)?`;
49
- const XRANGE_PLAIN_LOOSE = String.raw`[v=\s]*(${XRANGE_IDENTIFIER_LOOSE})(?:\.(${XRANGE_IDENTIFIER_LOOSE})(?:\.(${XRANGE_IDENTIFIER_LOOSE})(?:${PRERELEASE_LOOSE})?${BUILD}?)?)?`;
50
- const LONE_TILDE = "(?:~>?)";
51
- const LONE_CARET = String.raw`(?:\^)`;
52
- const COERCE_PLAIN = String.raw`(^|[^\d])(\d{1,${16}})(?:\.(\d{1,${16}}))?(?:\.(\d{1,${16}}))?`;
53
- const COERCE = String.raw`${COERCE_PLAIN}(?:$|[^\d])`;
54
- const COERCE_FULL = String.raw`${COERCE_PLAIN}(?:${PRERELEASE})?(?:${BUILD})?(?:$|[^\d])`;
55
- function makeSafeRegexSource(source) {
56
- const replacements = [
57
- [String.raw`\s`, 1],
58
- [String.raw`\d`, 256],
59
- [LETTER_DASH_NUMBER, 250]
60
- ];
61
- for (const [token, maximum] of replacements) source = source.split(`${token}*`).join(`${token}{0,${maximum}}`).split(`${token}+`).join(`${token}{1,${maximum}}`);
62
- return source;
63
- }
64
- function safeRegex(source, flags) {
65
- return new RegExp(makeSafeRegexSource(source), flags);
66
- }
67
- const NUMERIC$1 = /^\d+$/;
68
- function compareIdentifiers(left, right) {
69
- if (typeof left === "number" && typeof right === "number") return left === right ? 0 : left < right ? -1 : 1;
70
- const leftNumeric = NUMERIC$1.test(String(left));
71
- const rightNumeric = NUMERIC$1.test(String(right));
72
- const normalizedLeft = leftNumeric ? Number(left) : left;
73
- const normalizedRight = rightNumeric ? Number(right) : right;
74
- return normalizedLeft === normalizedRight ? 0 : leftNumeric && !rightNumeric ? -1 : rightNumeric && !leftNumeric ? 1 : normalizedLeft < normalizedRight ? -1 : 1;
75
- }
76
- const FULL = safeRegex(`^${FULL_PLAIN}$`);
77
- const LOOSE = safeRegex(`^${LOOSE_PLAIN}$`);
78
- safeRegex(`^${PRERELEASE}$`);
79
- safeRegex(`^${PRERELEASE_LOOSE}$`);
80
- const COERCE_EXACT = safeRegex(COERCE);
81
- const COERCE_FULL_EXACT = safeRegex(COERCE_FULL);
82
- const NUMERIC = /^\d+$/;
83
- function formatComparableVersion(version) {
84
- const base = `${version.major}.${version.minor}.${version.patch}`;
85
- return version.prerelease?.length ? `${base}-${version.prerelease.join(".")}` : base;
86
- }
87
- function formatFullVersion(version) {
88
- const comparable = formatComparableVersion(version);
89
- return version.build?.length ? `${comparable}+${version.build.join(".")}` : comparable;
90
- }
91
- function parse(version, options = {}) {
92
- if (typeof version !== "string") return version;
93
- if (version.length > 256) throw new TypeError(`Version exceeds the maximum length of 256 characters`);
94
- const match = version.trim().match(options.loose ? LOOSE : FULL);
95
- if (!match) throw new TypeError(`Invalid version syntax: ${version}`);
96
- const major = Number(match[1]);
97
- const minor = Number(match[2]);
98
- const patch = Number(match[3]);
99
- if (major > Number.MAX_SAFE_INTEGER || major < 0) throw new TypeError(`Invalid major version: ${match[1]}`);
100
- if (minor > Number.MAX_SAFE_INTEGER || minor < 0) throw new TypeError(`Invalid minor version: ${match[2]}`);
101
- if (patch > Number.MAX_SAFE_INTEGER || patch < 0) throw new TypeError(`Invalid patch version: ${match[3]}`);
102
- const prerelease = match[4] ? match[4].split(".").map((identifier) => {
103
- if (NUMERIC.test(identifier)) {
104
- const numeric = Number(identifier);
105
- if (numeric >= 0 && numeric < Number.MAX_SAFE_INTEGER) return numeric;
10
+ const countPostgresRows = async (db, input, where) => {
11
+ switch (input.model) {
12
+ case "bundles": {
13
+ let rows = db.selectFrom("bundles");
14
+ if (where !== void 0) rows = rows.where(where);
15
+ const query = input.distinct === void 0 ? rows.select(({ fn }) => fn.countAll().as("count")) : db.selectFrom(rows.select(input.distinct).distinct().as("distinct_rows")).select(({ fn }) => fn.countAll().as("count"));
16
+ return Number((await query.executeTakeFirstOrThrow()).count);
106
17
  }
107
- return identifier;
108
- }) : void 0;
109
- return {
110
- build: match[5]?.split("."),
111
- major,
112
- minor,
113
- patch,
114
- prerelease
115
- };
116
- }
117
- function tryParse(version, options = {}) {
118
- try {
119
- return parse(version, options);
120
- } catch {
121
- return null;
122
- }
123
- }
124
- function compareMainParsed(left, right) {
125
- return left.major === right.major ? left.minor === right.minor ? left.patch === right.patch ? 0 : left.patch < right.patch ? -1 : 1 : left.minor < right.minor ? -1 : 1 : left.major < right.major ? -1 : 1;
126
- }
127
- function comparePrereleaseParsed(left, right) {
128
- const leftPrerelease = left.prerelease;
129
- const rightPrerelease = right.prerelease;
130
- if (leftPrerelease?.length && !rightPrerelease?.length) return -1;
131
- if (!leftPrerelease?.length && rightPrerelease?.length) return 1;
132
- if (!leftPrerelease?.length && !rightPrerelease?.length) return 0;
133
- for (let index = 0;; index++) {
134
- const leftIdentifier = leftPrerelease?.[index];
135
- const rightIdentifier = rightPrerelease?.[index];
136
- if (leftIdentifier === void 0 && rightIdentifier === void 0) return 0;
137
- if (rightIdentifier === void 0) return 1;
138
- if (leftIdentifier === void 0) return -1;
139
- if (leftIdentifier !== rightIdentifier) return compareIdentifiers(leftIdentifier, rightIdentifier);
140
- }
141
- }
142
- function compareParsed(left, right) {
143
- return compareMainParsed(left, right) || comparePrereleaseParsed(left, right);
144
- }
145
- function coerceParsedVersion(value, options = {}) {
146
- if (typeof value === "object") return value;
147
- const input = typeof value === "number" ? String(value) : value;
148
- if (typeof input !== "string") return null;
149
- let match = null;
150
- if (options.rtl) {
151
- const expression = safeRegex(options.includePrerelease ? COERCE_FULL : COERCE, "g");
152
- let next;
153
- while ((next = expression.exec(input)) && (!match || match.index + match[0].length !== input.length)) {
154
- if (!match || next.index + next[0].length !== match.index + match[0].length) match = next;
155
- expression.lastIndex = next.index + next[1].length + next[2].length;
156
- }
157
- } else match = (options.includePrerelease ? COERCE_FULL_EXACT : COERCE_EXACT).exec(input);
158
- if (!match) return null;
159
- const major = match[2];
160
- return tryParse(`${major}.${match[3] || "0"}.${match[4] || "0"}${options.includePrerelease && match[5] ? `-${match[5]}` : ""}${options.includePrerelease && match[6] ? `+${match[6]}` : ""}`, options);
161
- }
162
- const STRICT_COMPARATOR = safeRegex(String.raw`^${GREATER_LESS_THAN}\s*(${FULL_PLAIN})$|^$`);
163
- const LOOSE_COMPARATOR$1 = safeRegex(String.raw`^${GREATER_LESS_THAN}\s*(${LOOSE_PLAIN})$|^$`);
164
- function parseComparator(comparator, options = {}) {
165
- const normalized = comparator.trim().replaceAll(/\s+/g, " ");
166
- const match = normalized.match(options.loose ? LOOSE_COMPARATOR$1 : STRICT_COMPARATOR);
167
- if (!match) throw new TypeError(`Invalid comparator: ${normalized}`);
168
- const operator = match[1] === "=" ? "" : match[1] || "";
169
- const version = match[2] ? parse(match[2], options) : null;
170
- return {
171
- operator,
172
- options,
173
- value: version ? `${operator}${formatComparableVersion(version)}` : "",
174
- version
175
- };
176
- }
177
- function testParsedComparator(comparator, version) {
178
- if (!comparator.version) return true;
179
- const comparison = compareParsed(version, comparator.version);
180
- switch (comparator.operator) {
181
- case "": return comparison === 0;
182
- case ">": return comparison > 0;
183
- case ">=": return comparison >= 0;
184
- case "<": return comparison < 0;
185
- case "<=": return comparison <= 0;
186
- }
187
- }
188
- function comparatorAllowsPrerelease(comparator, version) {
189
- const allowed = comparator.version;
190
- return allowed !== null && !!allowed.prerelease?.length && allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch;
191
- }
192
- function testComparatorSet(set, version, options) {
193
- if (set.some((comparator) => !testParsedComparator(comparator, version))) return false;
194
- return !version.prerelease?.length || !!options.includePrerelease || set.some((comparator) => comparatorAllowsPrerelease(comparator, version));
195
- }
196
- const BUILD_STRIP = new RegExp(BUILD, "g");
197
- const BUILD_SAFE = safeRegex(BUILD);
198
- const STRICT_HYPHEN = safeRegex(String.raw`^\s*(${XRANGE_PLAIN})\s+-\s+(${XRANGE_PLAIN})\s*$`);
199
- const LOOSE_HYPHEN = safeRegex(String.raw`^\s*(${XRANGE_PLAIN_LOOSE})\s+-\s+(${XRANGE_PLAIN_LOOSE})\s*$`);
200
- const COMPARATOR_TRIM = safeRegex(String.raw`(\s*)${GREATER_LESS_THAN}\s*(${LOOSE_PLAIN}|${XRANGE_PLAIN})`, "g");
201
- const TILDE_TRIM = safeRegex(String.raw`(\s*)${LONE_TILDE}\s+`, "g");
202
- const CARET_TRIM = safeRegex(String.raw`(\s*)${LONE_CARET}\s+`, "g");
203
- const STRICT_TILDE = safeRegex(`^${LONE_TILDE}${XRANGE_PLAIN}$`);
204
- const LOOSE_TILDE = safeRegex(`^${LONE_TILDE}${XRANGE_PLAIN_LOOSE}$`);
205
- const STRICT_CARET = safeRegex(`^${LONE_CARET}${XRANGE_PLAIN}$`);
206
- const LOOSE_CARET = safeRegex(`^${LONE_CARET}${XRANGE_PLAIN_LOOSE}$`);
207
- const STRICT_XRANGE = safeRegex(String.raw`^${GREATER_LESS_THAN}\s*${XRANGE_PLAIN}$`);
208
- const LOOSE_XRANGE = safeRegex(String.raw`^${GREATER_LESS_THAN}\s*${XRANGE_PLAIN_LOOSE}$`);
209
- const STAR = safeRegex(String.raw`(<|>)?=?\s*\*`);
210
- const GTE_ZERO = /^\s*>=\s*0\.0\.0\s*$/;
211
- const GTE_ZERO_PRERELEASE = /^\s*>=\s*0\.0\.0-0\s*$/;
212
- const LOOSE_COMPARATOR = safeRegex(String.raw`^${GREATER_LESS_THAN}\s*(${LOOSE_PLAIN})$|^$`);
213
- function isWildcard(value) {
214
- return !value || String(value).toLowerCase() === "x" || String(value) === "*";
215
- }
216
- function hasInvalidWildcardOrder(major, minor, patch) {
217
- return isWildcard(major) && !isWildcard(minor) || isWildcard(minor) && Boolean(patch) && !isWildcard(patch);
218
- }
219
- function replaceTilde(comparator, options) {
220
- const expression = options.loose ? LOOSE_TILDE : STRICT_TILDE;
221
- const lowerPrerelease = options.includePrerelease ? "-0" : "";
222
- return comparator.replace(expression, (_match, major, minor, patch, prerelease) => {
223
- if (isWildcard(major)) return "";
224
- if (isWildcard(minor)) return `>=${major}.0.0${lowerPrerelease} <${Number(major) + 1}.0.0-0`;
225
- if (isWildcard(patch)) return `>=${major}.${minor}.0${lowerPrerelease} <${major}.${Number(minor) + 1}.0-0`;
226
- return prerelease ? `>=${major}.${minor}.${patch}-${prerelease} <${major}.${Number(minor) + 1}.0-0` : `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0`;
227
- });
228
- }
229
- function replaceTildes(comparator, options) {
230
- return comparator.trim().split(/\s+/).map((part) => replaceTilde(part, options)).join(" ");
231
- }
232
- function replaceCaret(comparator, options) {
233
- const expression = options.loose ? LOOSE_CARET : STRICT_CARET;
234
- const lowerPrerelease = options.includePrerelease ? "-0" : "";
235
- return comparator.replace(expression, (_match, major, minor, patch, prerelease) => {
236
- if (isWildcard(major)) return "";
237
- if (isWildcard(minor)) return `>=${major}.0.0${lowerPrerelease} <${Number(major) + 1}.0.0-0`;
238
- if (isWildcard(patch)) return major === "0" ? `>=${major}.${minor}.0${lowerPrerelease} <${major}.${Number(minor) + 1}.0-0` : `>=${major}.${minor}.0${lowerPrerelease} <${Number(major) + 1}.0.0-0`;
239
- if (prerelease) return major === "0" ? minor === "0" ? `>=${major}.${minor}.${patch}-${prerelease} <${major}.${minor}.${Number(patch) + 1}-0` : `>=${major}.${minor}.${patch}-${prerelease} <${major}.${Number(minor) + 1}.0-0` : `>=${major}.${minor}.${patch}-${prerelease} <${Number(major) + 1}.0.0-0`;
240
- return major === "0" ? minor === "0" ? `>=${major}.${minor}.${patch} <${major}.${minor}.${Number(patch) + 1}-0` : `>=${major}.${minor}.${patch} <${major}.${Number(minor) + 1}.0-0` : `>=${major}.${minor}.${patch} <${Number(major) + 1}.0.0-0`;
241
- });
242
- }
243
- function replaceCarets(comparator, options) {
244
- return comparator.trim().split(/\s+/).map((part) => replaceCaret(part, options)).join(" ");
245
- }
246
- function replaceXRange(comparator, options) {
247
- const expression = options.loose ? LOOSE_XRANGE : STRICT_XRANGE;
248
- return comparator.trim().replace(expression, (match, rawOperator, rawMajor, rawMinor, rawPatch) => {
249
- let operator = rawOperator;
250
- let major = rawMajor;
251
- let minor = rawMinor;
252
- let patch = rawPatch;
253
- if (hasInvalidWildcardOrder(String(major), minor === void 0 ? void 0 : String(minor), patch === void 0 ? void 0 : String(patch))) return comparator;
254
- const wildcardMajor = isWildcard(major);
255
- const wildcardMinor = wildcardMajor || isWildcard(minor);
256
- const wildcardPatch = wildcardMinor || isWildcard(patch);
257
- if (operator === "=" && wildcardPatch) operator = "";
258
- if (wildcardMajor) return operator === ">" || operator === "<" ? "<0.0.0-0" : "*";
259
- let prerelease = options.includePrerelease ? "-0" : "";
260
- if (operator && wildcardPatch) {
261
- if (wildcardMinor) minor = 0;
262
- patch = 0;
263
- if (operator === ">") {
264
- operator = ">=";
265
- if (wildcardMinor) {
266
- major = Number(major) + 1;
267
- minor = 0;
268
- } else minor = Number(minor) + 1;
269
- } else if (operator === "<=") {
270
- operator = "<";
271
- if (wildcardMinor) major = Number(major) + 1;
272
- else minor = Number(minor) + 1;
273
- }
274
- if (operator === "<") prerelease = "-0";
275
- return `${operator}${major}.${minor}.${patch}${prerelease}`;
276
- }
277
- if (wildcardMinor) return `>=${major}.0.0${prerelease} <${Number(major) + 1}.0.0-0`;
278
- if (wildcardPatch) return `>=${major}.${minor}.0${prerelease} <${major}.${Number(minor) + 1}.0-0`;
279
- return match;
280
- });
281
- }
282
- function replaceXRanges(comparator, options) {
283
- return comparator.split(/\s+/).map((part) => replaceXRange(part, options)).join(" ");
284
- }
285
- function replaceHyphenRange(range, options) {
286
- const expression = options.loose ? LOOSE_HYPHEN : STRICT_HYPHEN;
287
- return range.replace(expression, (_match, rawFrom, fromMajor, fromMinor, fromPatch, fromPrerelease, _fromBuild, rawTo, toMajor, toMinor, toPatch, toPrerelease) => {
288
- let from = rawFrom;
289
- let to = rawTo;
290
- if (isWildcard(fromMajor)) from = "";
291
- else if (isWildcard(fromMinor)) from = `>=${fromMajor}.0.0${options.includePrerelease ? "-0" : ""}`;
292
- else if (isWildcard(fromPatch)) from = `>=${fromMajor}.${fromMinor}.0${options.includePrerelease ? "-0" : ""}`;
293
- else if (fromPrerelease) from = `>=${from}`;
294
- else from = `>=${from}${options.includePrerelease ? "-0" : ""}`;
295
- if (isWildcard(toMajor)) to = "";
296
- else if (isWildcard(toMinor)) to = `<${Number(toMajor) + 1}.0.0-0`;
297
- else if (isWildcard(toPatch)) to = `<${toMajor}.${Number(toMinor) + 1}.0-0`;
298
- else if (toPrerelease) to = `<=${toMajor}.${toMinor}.${toPatch}-${toPrerelease}`;
299
- else if (options.includePrerelease) to = `<${toMajor}.${toMinor}.${Number(toPatch) + 1}-0`;
300
- else to = `<=${to}`;
301
- return `${from} ${to}`.trim();
302
- });
303
- }
304
- function expandComparator(comparator, options) {
305
- return replaceXRanges(replaceTildes(replaceCarets(comparator.replace(BUILD_SAFE, ""), options), options), options).trim().replace(STAR, "");
306
- }
307
- function parseSimpleRange(input, options) {
308
- let parts = replaceHyphenRange(input.replace(BUILD_STRIP, ""), options).replace(COMPARATOR_TRIM, "$1$2$3").replace(TILDE_TRIM, "$1~").replace(CARET_TRIM, "$1^").split(" ").map((part) => expandComparator(part, options)).join(" ").split(/\s+/).map((part) => part.trim().replace(options.includePrerelease ? GTE_ZERO_PRERELEASE : GTE_ZERO, ""));
309
- if (options.loose) parts = parts.filter((part) => LOOSE_COMPARATOR.test(part));
310
- const unique = /* @__PURE__ */ new Map();
311
- for (const comparator of parts.map((part) => parseComparator(part, options))) {
312
- if (comparator.value === "<0.0.0-0") return [comparator];
313
- unique.set(comparator.value, comparator);
314
- }
315
- if (unique.size > 1) unique.delete("");
316
- return [...unique.values()];
317
- }
318
- function parseRange(range, options = {}) {
319
- if (typeof range !== "string") return range;
320
- const parsedOptions = { ...options };
321
- const raw = range.trim().replaceAll(/\s+/g, " ");
322
- let sets = raw.split("||").map((part) => parseSimpleRange(part.trim(), parsedOptions)).filter((set) => set.length);
323
- if (!sets.length) throw new TypeError(`Range contains no valid comparator sets: ${raw}`);
324
- if (sets.length > 1) {
325
- const first = sets[0];
326
- sets = sets.filter((set) => set[0]?.value !== "<0.0.0-0");
327
- if (!sets.length) sets = [first];
328
- else if (sets.length > 1) {
329
- const any = sets.find((set) => set.length === 1 && set[0]?.value === "");
330
- if (any) sets = [any];
18
+ case "bundle_patches": {
19
+ let rows = db.selectFrom("bundle_patches");
20
+ if (where !== void 0) rows = rows.where(where);
21
+ const query = input.distinct === void 0 ? rows.select(({ fn }) => fn.countAll().as("count")) : db.selectFrom(rows.select(input.distinct).distinct().as("distinct_rows")).select(({ fn }) => fn.countAll().as("count"));
22
+ return Number((await query.executeTakeFirstOrThrow()).count);
331
23
  }
332
- }
333
- return {
334
- normalized: sets.map((set) => set.map((comparator) => comparator.value).join(" ")).join("||"),
335
- options: parsedOptions,
336
- raw,
337
- sets
338
- };
339
- }
340
- function tryParseRange(range, options = {}) {
341
- try {
342
- return parseRange(range, options);
343
- } catch {
344
- return null;
345
- }
346
- }
347
- function testParsedRange(range, version) {
348
- return range.sets.some((set) => testComparatorSet(set, version, range.options));
349
- }
350
- function testRangeVersion(range, version) {
351
- const parsed = tryParse(version, range.options);
352
- return parsed ? testParsedRange(range, parsed) : false;
353
- }
354
- function satisfies(version, range, options = {}) {
355
- const parsed = tryParseRange(range, options);
356
- return parsed ? testRangeVersion(parsed, version) : false;
357
- }
358
- function coerce(value, options = {}) {
359
- const parsed = coerceParsedVersion(value, options);
360
- return parsed ? formatFullVersion(parsed) : null;
361
- }
362
- const semverSatisfies = (targetAppVersion, currentVersion) => {
363
- const currentCoerce = coerce(currentVersion);
364
- if (!currentCoerce) return false;
365
- return satisfies(currentCoerce, targetAppVersion);
366
- };
367
- /**
368
- * Filters target app versions that are compatible with the current app version.
369
- * Returns only versions that are compatible with the current version according to semver rules.
370
- *
371
- * @param targetAppVersionList - List of target app versions to filter
372
- * @param currentVersion - Current app version
373
- * @returns Array of target app versions compatible with the current version
374
- */
375
- const filterCompatibleAppVersions = (targetAppVersionList, currentVersion) => {
376
- return targetAppVersionList.filter((version) => semverSatisfies(version, currentVersion)).sort((a, b) => b.localeCompare(a));
377
- };
378
- new TextEncoder();
379
- new TextDecoder();
380
- const day = 3600 * 24;
381
- day * 7;
382
- day * 365.25;
383
- //#endregion
384
- //#region ../../node_modules/.pnpm/map-obj@5.0.0/node_modules/map-obj/index.js
385
- const isObject$1 = (value) => typeof value === "object" && value !== null;
386
- const isObjectCustom = (value) => isObject$1(value) && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date);
387
- const mapObjectSkip = Symbol("mapObjectSkip");
388
- const _mapObject = (object, mapper, options, isSeen = /* @__PURE__ */ new WeakMap()) => {
389
- options = {
390
- deep: false,
391
- target: {},
392
- ...options
393
- };
394
- if (isSeen.has(object)) return isSeen.get(object);
395
- isSeen.set(object, options.target);
396
- const { target } = options;
397
- delete options.target;
398
- const mapArray = (array) => array.map((element) => isObjectCustom(element) ? _mapObject(element, mapper, options, isSeen) : element);
399
- if (Array.isArray(object)) return mapArray(object);
400
- for (const [key, value] of Object.entries(object)) {
401
- const mapResult = mapper(key, value, object);
402
- if (mapResult === mapObjectSkip) continue;
403
- let [newKey, newValue, { shouldRecurse = true } = {}] = mapResult;
404
- if (newKey === "__proto__") continue;
405
- if (options.deep && shouldRecurse && isObjectCustom(newValue)) newValue = Array.isArray(newValue) ? mapArray(newValue) : _mapObject(newValue, mapper, options, isSeen);
406
- target[newKey] = newValue;
407
- }
408
- return target;
409
- };
410
- function mapObject(object, mapper, options) {
411
- if (!isObject$1(object)) throw new TypeError(`Expected an object, got \`${object}\` (${typeof object})`);
412
- return _mapObject(object, mapper, options);
413
- }
414
- //#endregion
415
- //#region ../../node_modules/.pnpm/camelcase@8.0.0/node_modules/camelcase/index.js
416
- const UPPERCASE = /[\p{Lu}]/u;
417
- const LOWERCASE = /[\p{Ll}]/u;
418
- const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
419
- const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
420
- const SEPARATORS = /[_.\- ]+/;
421
- const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
422
- const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
423
- const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
424
- const preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase) => {
425
- let isLastCharLower = false;
426
- let isLastCharUpper = false;
427
- let isLastLastCharUpper = false;
428
- let isLastLastCharPreserved = false;
429
- for (let index = 0; index < string.length; index++) {
430
- const character = string[index];
431
- isLastLastCharPreserved = index > 2 ? string[index - 3] === "-" : true;
432
- if (isLastCharLower && UPPERCASE.test(character)) {
433
- string = string.slice(0, index) + "-" + string.slice(index);
434
- isLastCharLower = false;
435
- isLastLastCharUpper = isLastCharUpper;
436
- isLastCharUpper = true;
437
- index++;
438
- } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase)) {
439
- string = string.slice(0, index - 1) + "-" + string.slice(index - 1);
440
- isLastLastCharUpper = isLastCharUpper;
441
- isLastCharUpper = false;
442
- isLastCharLower = true;
443
- } else {
444
- isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
445
- isLastLastCharUpper = isLastCharUpper;
446
- isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
24
+ case "releases": {
25
+ let rows = db.selectFrom("releases");
26
+ if (where !== void 0) rows = rows.where(where);
27
+ const query = rows.select(({ fn }) => fn.countAll().as("count"));
28
+ return Number((await query.executeTakeFirstOrThrow()).count);
447
29
  }
448
30
  }
449
- return string;
450
- };
451
- const preserveConsecutiveUppercase = (input, toLowerCase) => {
452
- LEADING_CAPITAL.lastIndex = 0;
453
- return input.replaceAll(LEADING_CAPITAL, (match) => toLowerCase(match));
454
- };
455
- const postProcess = (input, toUpperCase) => {
456
- SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
457
- NUMBERS_AND_IDENTIFIER.lastIndex = 0;
458
- return input.replaceAll(NUMBERS_AND_IDENTIFIER, (match, pattern, offset) => ["_", "-"].includes(input.charAt(offset + match.length)) ? match : toUpperCase(match)).replaceAll(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier));
459
31
  };
460
- function camelCase(input, options) {
461
- if (!(typeof input === "string" || Array.isArray(input))) throw new TypeError("Expected the input to be `string | string[]`");
462
- options = {
463
- pascalCase: false,
464
- preserveConsecutiveUppercase: false,
465
- ...options
466
- };
467
- if (Array.isArray(input)) input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
468
- else input = input.trim();
469
- if (input.length === 0) return "";
470
- const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
471
- const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
472
- if (input.length === 1) {
473
- if (SEPARATORS.test(input)) return "";
474
- return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
475
- }
476
- if (input !== toLowerCase(input)) input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
477
- input = input.replace(LEADING_SEPARATORS, "");
478
- input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
479
- if (options.pascalCase) input = toUpperCase(input.charAt(0)) + input.slice(1);
480
- return postProcess(input, toUpperCase);
481
- }
482
- //#endregion
483
- //#region ../../node_modules/.pnpm/quick-lru@6.1.2/node_modules/quick-lru/index.js
484
- var QuickLRU = class extends Map {
485
- constructor(options = {}) {
486
- super();
487
- if (!(options.maxSize && options.maxSize > 0)) throw new TypeError("`maxSize` must be a number greater than 0");
488
- if (typeof options.maxAge === "number" && options.maxAge === 0) throw new TypeError("`maxAge` must be a number greater than 0");
489
- this.maxSize = options.maxSize;
490
- this.maxAge = options.maxAge || Number.POSITIVE_INFINITY;
491
- this.onEviction = options.onEviction;
492
- this.cache = /* @__PURE__ */ new Map();
493
- this.oldCache = /* @__PURE__ */ new Map();
494
- this._size = 0;
495
- }
496
- _emitEvictions(cache) {
497
- if (typeof this.onEviction !== "function") return;
498
- for (const [key, item] of cache) this.onEviction(key, item.value);
499
- }
500
- _deleteIfExpired(key, item) {
501
- if (typeof item.expiry === "number" && item.expiry <= Date.now()) {
502
- if (typeof this.onEviction === "function") this.onEviction(key, item.value);
503
- return this.delete(key);
504
- }
505
- return false;
506
- }
507
- _getOrDeleteIfExpired(key, item) {
508
- if (this._deleteIfExpired(key, item) === false) return item.value;
509
- }
510
- _getItemValue(key, item) {
511
- return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
512
- }
513
- _peek(key, cache) {
514
- const item = cache.get(key);
515
- return this._getItemValue(key, item);
516
- }
517
- _set(key, value) {
518
- this.cache.set(key, value);
519
- this._size++;
520
- if (this._size >= this.maxSize) {
521
- this._size = 0;
522
- this._emitEvictions(this.oldCache);
523
- this.oldCache = this.cache;
524
- this.cache = /* @__PURE__ */ new Map();
525
- }
526
- }
527
- _moveToRecent(key, item) {
528
- this.oldCache.delete(key);
529
- this._set(key, item);
530
- }
531
- *_entriesAscending() {
532
- for (const item of this.oldCache) {
533
- const [key, value] = item;
534
- if (!this.cache.has(key)) {
535
- if (this._deleteIfExpired(key, value) === false) yield item;
536
- }
537
- }
538
- for (const item of this.cache) {
539
- const [key, value] = item;
540
- if (this._deleteIfExpired(key, value) === false) yield item;
541
- }
542
- }
543
- get(key) {
544
- if (this.cache.has(key)) {
545
- const item = this.cache.get(key);
546
- return this._getItemValue(key, item);
32
+ const findManyPostgresRows = async (db, input, where) => {
33
+ switch (input.model) {
34
+ case "bundles": {
35
+ let query = db.selectFrom("bundles").selectAll();
36
+ if (where !== void 0) query = query.where(where);
37
+ if (input.distinctOn !== void 0) query = query.distinctOn(input.distinctOn.fields);
38
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
39
+ return query.limit(input.limit).offset(input.offset).execute();
547
40
  }
548
- if (this.oldCache.has(key)) {
549
- const item = this.oldCache.get(key);
550
- if (this._deleteIfExpired(key, item) === false) {
551
- this._moveToRecent(key, item);
552
- return item.value;
553
- }
41
+ case "release_catalogs": {
42
+ let query = db.selectFrom("release_catalogs").selectAll();
43
+ if (where !== void 0) query = query.where(where);
44
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
45
+ return query.limit(input.limit).offset(input.offset).execute();
554
46
  }
555
- }
556
- set(key, value, { maxAge = this.maxAge } = {}) {
557
- const expiry = typeof maxAge === "number" && maxAge !== Number.POSITIVE_INFINITY ? Date.now() + maxAge : void 0;
558
- if (this.cache.has(key)) this.cache.set(key, {
559
- value,
560
- expiry
561
- });
562
- else this._set(key, {
563
- value,
564
- expiry
565
- });
566
- return this;
567
- }
568
- has(key) {
569
- if (this.cache.has(key)) return !this._deleteIfExpired(key, this.cache.get(key));
570
- if (this.oldCache.has(key)) return !this._deleteIfExpired(key, this.oldCache.get(key));
571
- return false;
572
- }
573
- peek(key) {
574
- if (this.cache.has(key)) return this._peek(key, this.cache);
575
- if (this.oldCache.has(key)) return this._peek(key, this.oldCache);
576
- }
577
- delete(key) {
578
- const deleted = this.cache.delete(key);
579
- if (deleted) this._size--;
580
- return this.oldCache.delete(key) || deleted;
581
- }
582
- clear() {
583
- this.cache.clear();
584
- this.oldCache.clear();
585
- this._size = 0;
586
- }
587
- resize(newSize) {
588
- if (!(newSize && newSize > 0)) throw new TypeError("`maxSize` must be a number greater than 0");
589
- const items = [...this._entriesAscending()];
590
- const removeCount = items.length - newSize;
591
- if (removeCount < 0) {
592
- this.cache = new Map(items);
593
- this.oldCache = /* @__PURE__ */ new Map();
594
- this._size = items.length;
595
- } else {
596
- if (removeCount > 0) this._emitEvictions(items.slice(0, removeCount));
597
- this.oldCache = new Map(items.slice(removeCount));
598
- this.cache = /* @__PURE__ */ new Map();
599
- this._size = 0;
47
+ case "bundle_events": {
48
+ let query = db.selectFrom("bundle_events").selectAll();
49
+ if (where !== void 0) query = query.where(where);
50
+ if (input.distinctOn !== void 0) query = query.distinctOn(input.distinctOn.fields);
51
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
52
+ return query.limit(input.limit).offset(input.offset).execute();
600
53
  }
601
- this.maxSize = newSize;
602
- }
603
- *keys() {
604
- for (const [key] of this) yield key;
605
- }
606
- *values() {
607
- for (const [, value] of this) yield value;
608
- }
609
- *[Symbol.iterator]() {
610
- for (const item of this.cache) {
611
- const [key, value] = item;
612
- if (this._deleteIfExpired(key, value) === false) yield [key, value.value];
54
+ case "channels": {
55
+ let query = db.selectFrom("channels").selectAll();
56
+ if (where !== void 0) query = query.where(where);
57
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
58
+ return query.limit(input.limit).offset(input.offset).execute();
613
59
  }
614
- for (const item of this.oldCache) {
615
- const [key, value] = item;
616
- if (!this.cache.has(key)) {
617
- if (this._deleteIfExpired(key, value) === false) yield [key, value.value];
618
- }
60
+ case "api_keys": {
61
+ let query = db.selectFrom("api_keys").selectAll();
62
+ if (where !== void 0) query = query.where(where);
63
+ if (input.distinctOn !== void 0) query = query.distinctOn(input.distinctOn.fields);
64
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
65
+ return query.limit(input.limit).offset(input.offset).execute();
619
66
  }
620
- }
621
- *entriesDescending() {
622
- let items = [...this.cache];
623
- for (let i = items.length - 1; i >= 0; --i) {
624
- const [key, value] = items[i];
625
- if (this._deleteIfExpired(key, value) === false) yield [key, value.value];
67
+ case "bundle_patches": {
68
+ let query = db.selectFrom("bundle_patches").selectAll();
69
+ if (where !== void 0) query = query.where(where);
70
+ if (input.distinctOn !== void 0) query = query.distinctOn(input.distinctOn.fields);
71
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
72
+ return query.limit(input.limit).offset(input.offset).execute();
626
73
  }
627
- items = [...this.oldCache];
628
- for (let i = items.length - 1; i >= 0; --i) {
629
- const [key, value] = items[i];
630
- if (!this.cache.has(key)) {
631
- if (this._deleteIfExpired(key, value) === false) yield [key, value.value];
632
- }
74
+ case "releases": {
75
+ let query = db.selectFrom("releases").selectAll();
76
+ if (where !== void 0) query = query.where(where);
77
+ for (const clause of input.orderBy ?? []) query = query.orderBy(clause.field, (order) => applyOrder(order, clause));
78
+ return query.limit(input.limit).offset(input.offset).execute();
633
79
  }
634
80
  }
635
- *entriesAscending() {
636
- for (const [key, value] of this._entriesAscending()) yield [key, value.value];
637
- }
638
- get size() {
639
- if (!this._size) return this.oldCache.size;
640
- let oldCacheSize = 0;
641
- for (const key of this.oldCache.keys()) if (!this.cache.has(key)) oldCacheSize++;
642
- return Math.min(this._size + oldCacheSize, this.maxSize);
643
- }
644
- entries() {
645
- return this.entriesAscending();
646
- }
647
- forEach(callbackFunction, thisArgument = this) {
648
- for (const [key, value] of this.entriesAscending()) callbackFunction.call(thisArgument, value, key, this);
649
- }
650
- get [Symbol.toStringTag]() {
651
- return JSON.stringify([...this.entriesAscending()]);
652
- }
653
81
  };
654
82
  //#endregion
655
- //#region ../../node_modules/.pnpm/camelcase-keys@9.1.3/node_modules/camelcase-keys/index.js
656
- const has = (array, key) => array.some((element) => {
657
- if (typeof element === "string") return element === key;
658
- element.lastIndex = 0;
659
- return element.test(key);
660
- });
661
- const cache = new QuickLRU({ maxSize: 1e5 });
662
- const isObject = (value) => typeof value === "object" && value !== null && !(value instanceof RegExp) && !(value instanceof Error) && !(value instanceof Date);
663
- const transform = (input, options = {}) => {
664
- if (!isObject(input)) return input;
665
- const { exclude, pascalCase = false, stopPaths, deep = false, preserveConsecutiveUppercase = false } = options;
666
- const stopPathsSet = new Set(stopPaths);
667
- const makeMapper = (parentPath) => (key, value) => {
668
- if (deep && isObject(value)) {
669
- const path = parentPath === void 0 ? key : `${parentPath}.${key}`;
670
- if (!stopPathsSet.has(path)) value = mapObject(value, makeMapper(path));
671
- }
672
- if (!(exclude && has(exclude, key))) {
673
- const cacheKey = pascalCase ? `${key}_` : key;
674
- if (cache.has(cacheKey)) key = cache.get(cacheKey);
675
- else {
676
- const returnValue = camelCase(key, {
677
- pascalCase,
678
- locale: false,
679
- preserveConsecutiveUppercase
680
- });
681
- if (key.length < 100) cache.set(cacheKey, returnValue);
682
- key = returnValue;
683
- }
684
- }
685
- return [key, value];
686
- };
687
- return mapObject(input, makeMapper(void 0));
83
+ //#region src/postgres.ts
84
+ const { Pool } = pg;
85
+ var InvalidPostgresPredicateError = class extends Error {
86
+ name = "InvalidPostgresPredicateError";
688
87
  };
689
- function camelcaseKeys(input, options) {
690
- if (Array.isArray(input)) return Object.keys(input).map((key) => transform(input[key], options));
691
- return transform(input, options);
692
- }
693
- //#endregion
694
- //#region ../../node_modules/.pnpm/pg-minify@1.8.0/node_modules/pg-minify/lib/utils.js
695
- var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
696
- const { inspect } = __require("util");
697
- function getIndexPos(text, index) {
698
- let lineIdx = 0, colIdx = index, pos = 0;
699
- do {
700
- pos = text.indexOf("\n", pos);
701
- if (pos === -1 || index < pos + 1) break;
702
- lineIdx++;
703
- pos++;
704
- colIdx = index - pos;
705
- } while (pos < index);
706
- return {
707
- line: lineIdx + 1,
708
- column: colIdx + 1
709
- };
710
- }
711
- function messageGap(level) {
712
- return " ".repeat(level * 4);
713
- }
714
- function addInspection(type, cb) {
715
- type[inspect.custom] = cb;
88
+ const isForeignKeyViolation = (error) => typeof error === "object" && error !== null && Reflect.get(error, "code") === "23503";
89
+ const escapeLikePattern = (value) => value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
90
+ const stringPredicate = (condition, operator) => {
91
+ if (typeof condition.value !== "string") throw new InvalidPostgresPredicateError();
92
+ const column = sql.ref(condition.field);
93
+ const literal = escapeLikePattern(condition.value);
94
+ const pattern = operator === "contains" ? `%${literal}%` : operator === "starts_with" ? `${literal}%` : `%${literal}`;
95
+ return "mode" in condition && condition.mode === "insensitive" ? sql`lower(${column}) like lower(${pattern}) escape '\\'` : sql`${column} like ${pattern} escape '\\'`;
96
+ };
97
+ const predicate = (condition) => {
98
+ const column = sql.ref(condition.field);
99
+ const operator = condition.operator ?? "eq";
100
+ switch (operator) {
101
+ case "eq":
102
+ case "ne":
103
+ if (condition.value === null) return operator === "eq" ? sql`${column} is null` : sql`${column} is not null`;
104
+ if ("mode" in condition && condition.mode === "insensitive") return operator === "eq" ? sql`lower(${column}) = lower(${condition.value})` : sql`lower(${column}) <> lower(${condition.value})`;
105
+ return operator === "eq" ? sql`${column} = ${condition.value}` : sql`${column} <> ${condition.value}`;
106
+ case "gt": return sql`${column} > ${condition.value}`;
107
+ case "gte": return sql`${column} >= ${condition.value}`;
108
+ case "lt": return sql`${column} < ${condition.value}`;
109
+ case "lte": return sql`${column} <= ${condition.value}`;
110
+ case "in":
111
+ case "not_in":
112
+ if (!Array.isArray(condition.value)) throw new InvalidPostgresPredicateError();
113
+ if (condition.value.length === 0) return sql`${operator === "not_in"}`;
114
+ return operator === "in" ? sql`${column} in (${sql.join(condition.value)})` : sql`${column} not in (${sql.join(condition.value)})`;
115
+ case "contains":
116
+ case "starts_with":
117
+ case "ends_with": return stringPredicate(condition, operator);
716
118
  }
717
- module.exports = {
718
- getIndexPos,
719
- messageGap,
720
- addInspection
721
- };
722
- }));
723
- //#endregion
724
- //#region ../../node_modules/.pnpm/pg-minify@1.8.0/node_modules/pg-minify/lib/error.js
725
- var require_error = /* @__PURE__ */ __commonJSMin(((exports, module) => {
726
- const { EOL } = __require("os");
727
- const { addInspection, messageGap } = require_utils();
728
- const parsingErrorCode = {
729
- unclosedMLC: 0,
730
- unclosedText: 1,
731
- unclosedQI: 2,
732
- multiLineQI: 3
733
- };
734
- Object.freeze(parsingErrorCode);
735
- const errorMessages = [
736
- {
737
- name: "unclosedMLC",
738
- message: "Unclosed multi-line comment."
739
- },
740
- {
741
- name: "unclosedText",
742
- message: "Unclosed text block."
743
- },
744
- {
745
- name: "unclosedQI",
746
- message: "Unclosed quoted identifier."
747
- },
748
- {
749
- name: "multiLineQI",
750
- message: "Multi-line quoted identifiers are not supported."
119
+ };
120
+ const buildWhere = (where) => {
121
+ const [first, ...rest] = where ?? [];
122
+ if (first === void 0) return;
123
+ let expression = predicate(first);
124
+ for (const condition of rest) {
125
+ const next = predicate(condition);
126
+ expression = condition.connector === "OR" ? sql`(${expression} or ${next})` : sql`(${expression} and ${next})`;
127
+ }
128
+ return expression;
129
+ };
130
+ const createPostgresImplementation = (db) => ({
131
+ async create(input) {
132
+ switch (input.model) {
133
+ case "bundles": return db.insertInto("bundles").values(input.data).returningAll().executeTakeFirstOrThrow();
134
+ case "bundle_patches": return db.insertInto("bundle_patches").values(input.data).returningAll().executeTakeFirstOrThrow();
135
+ case "bundle_events": return db.insertInto("bundle_events").values(input.data).returningAll().executeTakeFirstOrThrow();
136
+ case "releases": return db.insertInto("releases").values(input.data).returningAll().executeTakeFirstOrThrow();
137
+ case "release_catalogs": return db.insertInto("release_catalogs").values(input.data).returningAll().executeTakeFirstOrThrow();
138
+ case "channels": {
139
+ const query = db.insertInto("channels").values(input.data);
140
+ return await (input.onConflict === "ignore" ? query.onConflict((conflict) => conflict.column("name").doNothing()) : query).returningAll().executeTakeFirst() ?? await db.selectFrom("channels").selectAll().where("name", "=", input.data.name).executeTakeFirstOrThrow();
141
+ }
142
+ case "api_keys": return await (input.onConflict === "ignore" ? db.insertInto("api_keys").values(input.data).onConflict((conflict) => conflict.column("hash").doNothing()) : db.insertInto("api_keys").values(input.data)).returningAll().executeTakeFirst() ?? await db.selectFrom("api_keys").selectAll().where("hash", "=", input.data.hash).executeTakeFirstOrThrow();
751
143
  }
752
- ];
753
- var SQLParsingError = class extends Error {
754
- constructor(code, position) {
755
- const err = errorMessages[code].message;
756
- const message = `Error parsing SQL at {line:${position.line},col:${position.column}}: ${err}`;
757
- super(message);
758
- this.name = this.constructor.name;
759
- this.error = err;
760
- this.code = code;
761
- this.position = position;
762
- Error.captureStackTrace(this, this.constructor);
144
+ },
145
+ async update(input) {
146
+ const where = buildWhere(input.where);
147
+ if (input.model === "api_keys") {
148
+ let query = db.updateTable("api_keys").set(input.update);
149
+ if (where !== void 0) query = query.where(where);
150
+ return await query.returningAll().executeTakeFirst() ?? null;
763
151
  }
764
- };
765
- SQLParsingError.prototype.toString = function(level) {
766
- level = level > 0 ? parseInt(level) : 0;
767
- const gap = messageGap(level + 1);
768
- return [
769
- "SQLParsingError {",
770
- `${gap}code: parsingErrorCode.${errorMessages[this.code].name}`,
771
- `${gap}error: "${this.error}"`,
772
- `${gap}position: {line: ${this.position.line}, col: ${this.position.column}}`,
773
- `${messageGap(level)}}`
774
- ].join(EOL);
775
- };
776
- addInspection(SQLParsingError.prototype, function() {
777
- return this.toString();
778
- });
779
- module.exports = {
780
- SQLParsingError,
781
- parsingErrorCode
782
- };
783
- }));
784
- //#endregion
785
- //#region ../../node_modules/.pnpm/pg-minify@1.8.0/node_modules/pg-minify/lib/parser.js
786
- var require_parser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
787
- const { parsingErrorCode, SQLParsingError } = require_error();
788
- const { getIndexPos } = require_utils();
789
- const compressors = ".,;:()[]=<>+-*/|!?@#";
790
- function minify(sql, options) {
791
- if (typeof sql !== "string") throw new TypeError("Input SQL must be a text string.");
792
- if (!sql.length) return "";
793
- sql = sql.replace(/\r\n/g, "\n");
794
- options = options || {};
795
- let idx = 0, result = "", space = false;
796
- const len = sql.length;
797
- do {
798
- const s = sql[idx], s1 = sql[idx + 1];
799
- if (isGap(s)) {
800
- while (++idx < len && isGap(sql[idx]));
801
- if (idx < len) space = true;
802
- idx--;
803
- continue;
152
+ if (input.model === "releases") {
153
+ let query = db.updateTable("releases").set(input.update);
154
+ if (where !== void 0) query = query.where(where);
155
+ return await query.returningAll().executeTakeFirst() ?? null;
156
+ }
157
+ if (input.model === "release_catalogs") {
158
+ let query = db.updateTable("release_catalogs").set(input.update);
159
+ if (where !== void 0) query = query.where(where);
160
+ return await query.returningAll().executeTakeFirst() ?? null;
161
+ }
162
+ let query = db.updateTable("bundles").set(input.update);
163
+ if (where !== void 0) query = query.where(where);
164
+ return await query.returningAll().executeTakeFirst() ?? null;
165
+ },
166
+ async delete(input) {
167
+ const where = buildWhere(input.where);
168
+ switch (input.model) {
169
+ case "bundles": {
170
+ let query = db.deleteFrom("bundles");
171
+ if (where !== void 0) query = query.where(where);
172
+ await query.execute();
173
+ return;
804
174
  }
805
- if (s === "-" && s1 === "-") {
806
- const lb = sql.indexOf("\n", idx + 2);
807
- if (lb < 0) break;
808
- idx = lb - 1;
809
- skipGaps();
810
- continue;
175
+ case "bundle_patches": {
176
+ let query = db.deleteFrom("bundle_patches");
177
+ if (where !== void 0) query = query.where(where);
178
+ await query.execute();
179
+ return;
811
180
  }
812
- if (s === "/" && s1 === "*") {
813
- let c = idx + 1, open = 0, close = 0, lastOpen, lastClose;
814
- while (++c < len - 1 && close <= open) if (sql[c] === "/" && sql[c + 1] === "*") {
815
- lastOpen = c;
816
- open++;
817
- c++;
818
- } else if (sql[c] === "*" && sql[c + 1] === "/") {
819
- lastClose = c;
820
- close++;
821
- c++;
822
- }
823
- if (close <= open) {
824
- idx = lastOpen;
825
- throwError(parsingErrorCode.unclosedMLC);
826
- }
827
- if (sql[idx + 2] === "!" && !options.removeAll) {
828
- if (options.compress) space = false;
829
- addSpace();
830
- result += sql.substring(idx, lastClose + 2).replace(/\n/g, "\r\n");
181
+ case "channels": {
182
+ let query = db.deleteFrom("channels");
183
+ if (where !== void 0) query = query.where(where);
184
+ try {
185
+ await query.execute();
186
+ } catch (error) {
187
+ if (isForeignKeyViolation(error)) throw new DatabaseRowReferencedError();
188
+ throw error;
831
189
  }
832
- idx = lastClose + 1;
833
- skipGaps();
834
- continue;
835
190
  }
836
- let closeIdx, text;
837
- if (s === "\"") {
838
- closeIdx = sql.indexOf("\"", idx + 1);
839
- if (closeIdx < 0) throwError(parsingErrorCode.unclosedQI);
840
- text = sql.substring(idx, closeIdx + 1);
841
- if (text.indexOf("\n") > 0) throwError(parsingErrorCode.multiLineQI);
842
- if (options.compress) space = false;
843
- addSpace();
844
- result += text;
845
- idx = closeIdx;
846
- skipGaps();
847
- continue;
191
+ case "releases": {
192
+ let query = db.deleteFrom("releases");
193
+ if (where !== void 0) query = query.where(where);
194
+ await query.execute();
848
195
  }
849
- if (s === "'") {
850
- closeIdx = idx;
851
- do {
852
- closeIdx = sql.indexOf("'", closeIdx + 1);
853
- if (closeIdx > 0) {
854
- let i = closeIdx;
855
- while (sql[--i] === "\\");
856
- if ((closeIdx - i) % 2) {
857
- let step = closeIdx;
858
- while (++step < len && sql[step] === "'");
859
- if ((step - closeIdx) % 2) {
860
- closeIdx = step - 1;
861
- break;
862
- }
863
- closeIdx = step === len ? -1 : step;
864
- }
865
- }
866
- } while (closeIdx > 0);
867
- if (closeIdx < 0) throwError(parsingErrorCode.unclosedText);
868
- if (options.compress) space = false;
869
- addSpace();
870
- text = sql.substring(idx, closeIdx + 1);
871
- const hasLB = text.indexOf("\n") > 0;
872
- if (hasLB) text = text.split("\n").map((m) => {
873
- return m.replace(/^\s+|\s+$/g, "");
874
- }).join("\\n");
875
- const hasTabs = text.indexOf(" ") > 0;
876
- if (hasLB || hasTabs) {
877
- const prev = idx ? sql[idx - 1] : "";
878
- if (prev !== "E" && prev !== "e") {
879
- const r = result ? result[result.length - 1] : "";
880
- if (r && r !== " " && compressors.indexOf(r) < 0) result += " ";
881
- result += "E";
882
- }
883
- if (hasTabs) text = text.replace(/\t/g, "\\t");
884
- }
885
- result += text;
886
- idx = closeIdx;
887
- skipGaps();
888
- continue;
196
+ }
197
+ },
198
+ count: (input) => countPostgresRows(db, input, buildWhere(input.where)),
199
+ async findOne(input) {
200
+ const where = buildWhere(input.where);
201
+ switch (input.model) {
202
+ case "bundles": {
203
+ let query = db.selectFrom("bundles").selectAll();
204
+ if (where !== void 0) query = query.where(where);
205
+ return await query.executeTakeFirst() ?? null;
889
206
  }
890
- if (options.compress && compressors.indexOf(s) >= 0) {
891
- space = false;
892
- skipGaps();
207
+ case "api_keys": {
208
+ let query = db.selectFrom("api_keys").selectAll();
209
+ if (where !== void 0) query = query.where(where);
210
+ return await query.executeTakeFirst() ?? null;
893
211
  }
894
- addSpace();
895
- result += s;
896
- } while (++idx < len);
897
- return result;
898
- function skipGaps() {
899
- if (options.compress) while (idx < len - 1 && isGap(sql[idx + 1]) && idx++);
900
- }
901
- function addSpace() {
902
- if (space) {
903
- if (result.length) result += " ";
904
- space = false;
212
+ case "bundle_patches": {
213
+ let query = db.selectFrom("bundle_patches").selectAll();
214
+ if (where !== void 0) query = query.where(where);
215
+ return await query.executeTakeFirst() ?? null;
905
216
  }
906
- }
907
- function throwError(code) {
908
- throw new SQLParsingError(code, getIndexPos(sql, idx));
909
- }
910
- }
911
- function isGap(s) {
912
- return s === " " || s === " " || s === "\r" || s === "\n";
913
- }
914
- module.exports = minify;
915
- }));
916
- //#endregion
917
- //#region src/getUpdateInfo.ts
918
- var import_lib = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
919
- const parser = require_parser();
920
- const error = require_error();
921
- parser.SQLParsingError = error.SQLParsingError;
922
- parser.parsingErrorCode = error.parsingErrorCode;
923
- module.exports = parser;
924
- })))(), 1);
925
- const appVersionStrategy = async (pool, { platform, appVersion, bundleId, minBundleId = NIL_UUID, channel = "production", cohort }) => {
926
- const sqlGetTargetAppVersionList = (0, import_lib.default)(`
927
- SELECT target_app_version
928
- FROM get_target_app_version_list($1, $2);
929
- `);
930
- const { rows: appVersionList } = await pool.query(sqlGetTargetAppVersionList, [platform, minBundleId]);
931
- const targetAppVersionList = filterCompatibleAppVersions(appVersionList?.map((group) => group.target_app_version) ?? [], appVersion);
932
- const sqlGetUpdateInfo = (0, import_lib.default)(`
933
- SELECT *
934
- FROM get_update_info_by_app_version(
935
- $1, -- platform
936
- $2, -- appVersion
937
- $3, -- bundleId
938
- $4, -- minBundleId (nullable)
939
- $5, -- channel
940
- $6, -- targetAppVersionList (text array)
941
- $7 -- cohort (nullable)
942
- );
943
- `);
944
- const result = await pool.query(sqlGetUpdateInfo, [
945
- platform,
946
- appVersion,
947
- bundleId,
948
- minBundleId ?? NIL_UUID,
949
- channel,
950
- targetAppVersionList,
951
- cohort ?? null
952
- ]);
953
- return result.rows[0] ? camelcaseKeys(result.rows[0]) : null;
954
- };
955
- const fingerprintStrategy = async (pool, { platform, fingerprintHash, bundleId, minBundleId = NIL_UUID, channel = "production", cohort }) => {
956
- const sqlGetUpdateInfo = (0, import_lib.default)(`
957
- SELECT *
958
- FROM get_update_info_by_fingerprint_hash(
959
- $1, -- platform
960
- $2, -- bundleId
961
- $3, -- minBundleId (nullable)
962
- $4, -- channel
963
- $5, -- fingerprintHash
964
- $6 -- cohort (nullable)
965
- );
966
- `);
967
- const result = await pool.query(sqlGetUpdateInfo, [
968
- platform,
969
- bundleId,
970
- minBundleId ?? NIL_UUID,
971
- channel,
972
- fingerprintHash,
973
- cohort ?? null
974
- ]);
975
- return result.rows[0] ? camelcaseKeys(result.rows[0]) : null;
976
- };
977
- const getUpdateInfo = (pool, args) => {
978
- if (args._updateStrategy === "appVersion") return appVersionStrategy(pool, args);
979
- return fingerprintStrategy(pool, args);
980
- };
981
- //#endregion
982
- //#region src/postgres.ts
983
- const normalizeMetadata = (value) => {
984
- if (!value) return;
985
- if (typeof value === "string") try {
986
- return normalizeMetadata(JSON.parse(value));
987
- } catch {
988
- return;
989
- }
990
- if (typeof value === "object" && !Array.isArray(value)) return value;
991
- };
992
- const buildBundlePatchId = (bundleId, baseBundleId) => `${bundleId}:${baseBundleId}`;
993
- const mapPatchRowToPatch = (row) => ({
994
- baseBundleId: row.base_bundle_id,
995
- baseFileHash: row.base_file_hash,
996
- patchFileHash: row.patch_file_hash,
997
- patchStorageUri: row.patch_storage_uri
998
- });
999
- const mapRowToBundle = (data, patchRows = []) => {
1000
- const rawMetadata = normalizeMetadata(data.metadata);
1001
- const patches = patchRows.slice().sort((left, right) => left.order_index - right.order_index || left.base_bundle_id.localeCompare(right.base_bundle_id)).map(mapPatchRowToPatch);
1002
- const primaryPatch = patches[0] ?? null;
1003
- return {
1004
- enabled: data.enabled,
1005
- shouldForceUpdate: data.should_force_update,
1006
- fileHash: data.file_hash,
1007
- gitCommitHash: data.git_commit_hash,
1008
- id: data.id,
1009
- message: data.message,
1010
- platform: data.platform,
1011
- targetAppVersion: data.target_app_version,
1012
- channel: data.channel,
1013
- storageUri: data.storage_uri,
1014
- fingerprintHash: data.fingerprint_hash,
1015
- metadata: stripBundleArtifactMetadata(rawMetadata),
1016
- manifestStorageUri: data.manifest_storage_uri ?? null,
1017
- manifestFileHash: data.manifest_file_hash ?? null,
1018
- assetBaseStorageUri: data.asset_base_storage_uri ?? null,
1019
- patches,
1020
- patchBaseBundleId: primaryPatch?.baseBundleId ?? null,
1021
- patchBaseFileHash: primaryPatch?.baseFileHash ?? null,
1022
- patchFileHash: primaryPatch?.patchFileHash ?? null,
1023
- patchStorageUri: primaryPatch?.patchStorageUri ?? null,
1024
- rolloutCohortCount: data.rollout_cohort_count,
1025
- targetCohorts: data.target_cohorts
1026
- };
1027
- };
1028
- const bundleToRowValues = (bundle) => ({
1029
- id: bundle.id,
1030
- enabled: bundle.enabled,
1031
- should_force_update: bundle.shouldForceUpdate,
1032
- file_hash: bundle.fileHash,
1033
- git_commit_hash: bundle.gitCommitHash,
1034
- message: bundle.message,
1035
- platform: bundle.platform,
1036
- target_app_version: bundle.targetAppVersion,
1037
- channel: bundle.channel,
1038
- storage_uri: bundle.storageUri,
1039
- fingerprint_hash: bundle.fingerprintHash,
1040
- metadata: stripBundleArtifactMetadata(bundle.metadata) ?? {},
1041
- manifest_storage_uri: getManifestStorageUri(bundle),
1042
- manifest_file_hash: getManifestFileHash(bundle),
1043
- asset_base_storage_uri: getAssetBaseStorageUri(bundle),
1044
- rollout_cohort_count: bundle.rolloutCohortCount ?? null,
1045
- target_cohorts: bundle.targetCohorts ?? null
1046
- });
1047
- const bundleToPatchRows = (bundle) => getBundlePatches(bundle).map((patch, index) => ({
1048
- id: buildBundlePatchId(bundle.id, patch.baseBundleId),
1049
- bundle_id: bundle.id,
1050
- base_bundle_id: patch.baseBundleId,
1051
- base_file_hash: patch.baseFileHash,
1052
- patch_file_hash: patch.patchFileHash,
1053
- patch_storage_uri: patch.patchStorageUri,
1054
- order_index: index
1055
- }));
1056
- const postgres = createDatabasePlugin({
1057
- name: "postgres",
1058
- factory: (config) => {
1059
- const pool = new Pool(config);
1060
- const db = new Kysely({ dialect: new PostgresDialect({ pool }) });
1061
- const fetchPatchMap = async (bundleIds) => {
1062
- const patchMap = /* @__PURE__ */ new Map();
1063
- if (bundleIds.length === 0) return patchMap;
1064
- const rows = await db.selectFrom("bundle_patches").selectAll().where("bundle_id", "in", bundleIds).orderBy("order_index", "asc").execute();
1065
- for (const row of rows) {
1066
- const current = patchMap.get(row.bundle_id) ?? [];
1067
- current.push(row);
1068
- patchMap.set(row.bundle_id, current);
217
+ case "channels": {
218
+ let query = db.selectFrom("channels").selectAll();
219
+ if (where !== void 0) query = query.where(where);
220
+ return await query.executeTakeFirst() ?? null;
221
+ }
222
+ case "releases": {
223
+ let query = db.selectFrom("releases").selectAll();
224
+ if (where !== void 0) query = query.where(where);
225
+ return await query.executeTakeFirst() ?? null;
226
+ }
227
+ case "release_catalogs": {
228
+ let query = db.selectFrom("release_catalogs").selectAll();
229
+ if (where !== void 0) query = query.where(where);
230
+ return await query.executeTakeFirst() ?? null;
1069
231
  }
1070
- return patchMap;
232
+ }
233
+ },
234
+ findMany: (input) => findManyPostgresRows(db, input, buildWhere(input.where)),
235
+ async insertChannel({ row }) {
236
+ const inserted = await db.insertInto("channels").values(row).onConflict((conflict) => conflict.column("name").doNothing()).returningAll().executeTakeFirst();
237
+ if (inserted !== void 0) return {
238
+ row: inserted,
239
+ inserted: true
1071
240
  };
1072
241
  return {
1073
- async onUnmount() {
1074
- await db.destroy();
1075
- await pool.end();
1076
- },
1077
- async getUpdateInfo(args) {
1078
- return getUpdateInfo(pool, args);
1079
- },
1080
- async getBundleById(bundleId) {
1081
- const [data, patchMap] = await Promise.all([db.selectFrom("bundles").selectAll().where("id", "=", bundleId).executeTakeFirst(), fetchPatchMap([bundleId])]);
1082
- if (!data) return null;
1083
- return mapRowToBundle(data, patchMap.get(bundleId) ?? []);
1084
- },
1085
- async getBundles(options) {
1086
- const { where, limit, orderBy } = options ?? {};
1087
- const offset = (options && "offset" in options ? options.offset : void 0) ?? 0;
1088
- let countQuery = db.selectFrom("bundles");
1089
- if (where?.channel) countQuery = countQuery.where("channel", "=", where.channel);
1090
- if (where?.platform) countQuery = countQuery.where("platform", "=", where.platform);
1091
- if (where?.enabled !== void 0) countQuery = countQuery.where("enabled", "=", where.enabled);
1092
- if (where?.fingerprintHash !== void 0) countQuery = where.fingerprintHash === null ? countQuery.where("fingerprint_hash", "is", null) : countQuery.where("fingerprint_hash", "=", where.fingerprintHash);
1093
- if (where?.targetAppVersion !== void 0) countQuery = where.targetAppVersion === null ? countQuery.where("target_app_version", "is", null) : countQuery.where("target_app_version", "=", where.targetAppVersion);
1094
- if (where?.targetAppVersionIn) countQuery = countQuery.where("target_app_version", "in", where.targetAppVersionIn);
1095
- if (where?.targetAppVersionNotNull) countQuery = countQuery.where("target_app_version", "is not", null);
1096
- if (where?.id?.eq) countQuery = countQuery.where("id", "=", where.id.eq);
1097
- if (where?.id?.gt) countQuery = countQuery.where("id", ">", where.id.gt);
1098
- if (where?.id?.gte) countQuery = countQuery.where("id", ">=", where.id.gte);
1099
- if (where?.id?.lt) countQuery = countQuery.where("id", "<", where.id.lt);
1100
- if (where?.id?.lte) countQuery = countQuery.where("id", "<=", where.id.lte);
1101
- if (where?.id?.in) countQuery = countQuery.where("id", "in", where.id.in);
1102
- const total = (await countQuery.select(db.fn.count("id").as("total")).executeTakeFirst())?.total || 0;
1103
- let query = db.selectFrom("bundles").orderBy("id", orderBy?.direction === "asc" ? "asc" : "desc");
1104
- if (where?.channel) query = query.where("channel", "=", where.channel);
1105
- if (where?.platform) query = query.where("platform", "=", where.platform);
1106
- if (where?.enabled !== void 0) query = query.where("enabled", "=", where.enabled);
1107
- if (where?.fingerprintHash !== void 0) query = where.fingerprintHash === null ? query.where("fingerprint_hash", "is", null) : query.where("fingerprint_hash", "=", where.fingerprintHash);
1108
- if (where?.targetAppVersion !== void 0) query = where.targetAppVersion === null ? query.where("target_app_version", "is", null) : query.where("target_app_version", "=", where.targetAppVersion);
1109
- if (where?.targetAppVersionIn) query = query.where("target_app_version", "in", where.targetAppVersionIn);
1110
- if (where?.targetAppVersionNotNull) query = query.where("target_app_version", "is not", null);
1111
- if (where?.id?.eq) query = query.where("id", "=", where.id.eq);
1112
- if (where?.id?.gt) query = query.where("id", ">", where.id.gt);
1113
- if (where?.id?.gte) query = query.where("id", ">=", where.id.gte);
1114
- if (where?.id?.lt) query = query.where("id", "<", where.id.lt);
1115
- if (where?.id?.lte) query = query.where("id", "<=", where.id.lte);
1116
- if (where?.id?.in) query = query.where("id", "in", where.id.in);
1117
- if (limit) query = query.limit(limit);
1118
- if (offset) query = query.offset(offset);
1119
- const data = await query.selectAll().execute();
1120
- const patchMap = await fetchPatchMap(data.map((bundle) => bundle.id));
1121
- return {
1122
- data: data.map((bundle) => mapRowToBundle(bundle, patchMap.get(bundle.id) ?? [])),
1123
- pagination: calculatePagination(total, {
1124
- limit,
1125
- offset
1126
- })
1127
- };
1128
- },
1129
- async getChannels() {
1130
- return (await db.selectFrom("bundles").select("channel").groupBy("channel").execute()).map((bundle) => bundle.channel);
1131
- },
1132
- async commitBundle({ changedSets }) {
1133
- if (changedSets.length === 0) return;
1134
- await db.transaction().execute(async (tx) => {
1135
- for (const op of changedSets) if (op.operation === "delete") {
1136
- await tx.deleteFrom("bundle_patches").where("bundle_id", "=", op.data.id).execute();
1137
- await tx.deleteFrom("bundle_patches").where("base_bundle_id", "=", op.data.id).execute();
1138
- if ((await tx.deleteFrom("bundles").where("id", "=", op.data.id).executeTakeFirst()).numDeletedRows === 0n) throw new Error(`Bundle with id ${op.data.id} not found`);
1139
- } else if (op.operation === "insert" || op.operation === "update") {
1140
- const bundle = op.data;
1141
- const values = bundleToRowValues(bundle);
1142
- const patchRows = bundleToPatchRows(bundle);
1143
- const { id: _id, ...updateValues } = values;
1144
- await tx.insertInto("bundles").values(values).onConflict((oc) => oc.column("id").doUpdateSet(updateValues)).execute();
1145
- await tx.deleteFrom("bundle_patches").where("bundle_id", "=", bundle.id).execute();
1146
- if (patchRows.length > 0) await tx.insertInto("bundle_patches").values(patchRows).execute();
1147
- }
1148
- });
1149
- }
242
+ row: await db.selectFrom("channels").selectAll().where("name", "=", row.name).executeTakeFirstOrThrow(),
243
+ inserted: false
1150
244
  };
1151
- }
245
+ },
246
+ async deleteChannel({ id }) {
247
+ try {
248
+ return await db.deleteFrom("channels").where("id", "=", id).returning("id").executeTakeFirst() === void 0 ? {
249
+ deleted: false,
250
+ reason: "not_found"
251
+ } : { deleted: true };
252
+ } catch (error) {
253
+ if (isForeignKeyViolation(error)) return {
254
+ deleted: false,
255
+ reason: "not_empty"
256
+ };
257
+ throw error;
258
+ }
259
+ },
260
+ transaction: (callback) => db.transaction().execute((transaction) => callback(createPostgresImplementation(transaction))),
261
+ dispose: () => db.destroy()
1152
262
  });
263
+ const postgres = (config) => {
264
+ const { dialect, ...poolConfig } = config;
265
+ const adapter = createDatabasePluginAdapter("postgres", dialect !== void 0 ? createPostgresImplementation(new Kysely({ dialect })) : createPostgresImplementation(new Kysely({ dialect: new PostgresDialect({ pool: new Pool(poolConfig) }) })));
266
+ return createDatabasePlugin({
267
+ name: "postgres",
268
+ models: adapter.models,
269
+ commit: adapter.commit,
270
+ dispose: adapter.dispose
271
+ });
272
+ };
1153
273
  //#endregion
1154
- export { appVersionStrategy, fingerprintStrategy, getUpdateInfo, postgres };
274
+ export { postgres };