@pol-studios/db 1.0.54 → 1.0.55

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.
Files changed (50) hide show
  1. package/dist/auth/context.js +4 -4
  2. package/dist/auth/hooks.js +5 -5
  3. package/dist/auth/index.js +5 -5
  4. package/dist/{chunk-FIAXWEBK.js → chunk-7YGDT46S.js} +4 -4
  5. package/dist/{chunk-BZSAPFFB.js → chunk-AA3VUWTP.js} +112 -16
  6. package/dist/chunk-AA3VUWTP.js.map +1 -0
  7. package/dist/{chunk-3Q74DK5K.js → chunk-AKCNWHXV.js} +2 -2
  8. package/dist/{chunk-UJWETW36.js → chunk-AKIRHA4Q.js} +527 -418
  9. package/dist/chunk-AKIRHA4Q.js.map +1 -0
  10. package/dist/{chunk-FMYXG4VN.js → chunk-BRFFTGVJ.js} +2 -2
  11. package/dist/{chunk-YA6MUTA7.js → chunk-FI6JAD5G.js} +3 -3
  12. package/dist/chunk-JOULSXOI.js +415 -0
  13. package/dist/chunk-JOULSXOI.js.map +1 -0
  14. package/dist/{chunk-OKYHI6JG.js → chunk-LF3V3ERS.js} +3 -3
  15. package/dist/{chunk-2XS2PM62.js → chunk-OC6S4XFL.js} +7 -7
  16. package/dist/{chunk-DP3YEVSX.js → chunk-WILXD5X3.js} +3 -3
  17. package/dist/{chunk-ZGQ7Q4ZU.js → chunk-WM25QE7E.js} +2 -2
  18. package/dist/{chunk-WQLIGVQR.js → chunk-WSKBZIEI.js} +4 -1
  19. package/dist/chunk-WSKBZIEI.js.map +1 -0
  20. package/dist/chunk-YUX6RGLZ.js +1858 -0
  21. package/dist/chunk-YUX6RGLZ.js.map +1 -0
  22. package/dist/{chunk-Z3EJX3VG.js → chunk-Z456IHCB.js} +3 -3
  23. package/dist/hooks/index.js +2 -2
  24. package/dist/index.js +13 -13
  25. package/dist/index.native.d.ts +56 -2
  26. package/dist/index.native.js +13 -13
  27. package/dist/index.web.js +13 -13
  28. package/dist/mutation/index.js +3 -3
  29. package/dist/parser/index.js +3 -3
  30. package/dist/query/index.js +4 -4
  31. package/dist/realtime/index.js +3 -3
  32. package/dist/types/index.js +4 -4
  33. package/dist/with-auth/index.js +7 -7
  34. package/package.json +5 -3
  35. package/dist/chunk-BZSAPFFB.js.map +0 -1
  36. package/dist/chunk-CTRY7JDP.js +0 -4112
  37. package/dist/chunk-CTRY7JDP.js.map +0 -1
  38. package/dist/chunk-INEUG6MC.js +0 -521
  39. package/dist/chunk-INEUG6MC.js.map +0 -1
  40. package/dist/chunk-UJWETW36.js.map +0 -1
  41. package/dist/chunk-WQLIGVQR.js.map +0 -1
  42. /package/dist/{chunk-FIAXWEBK.js.map → chunk-7YGDT46S.js.map} +0 -0
  43. /package/dist/{chunk-3Q74DK5K.js.map → chunk-AKCNWHXV.js.map} +0 -0
  44. /package/dist/{chunk-FMYXG4VN.js.map → chunk-BRFFTGVJ.js.map} +0 -0
  45. /package/dist/{chunk-YA6MUTA7.js.map → chunk-FI6JAD5G.js.map} +0 -0
  46. /package/dist/{chunk-OKYHI6JG.js.map → chunk-LF3V3ERS.js.map} +0 -0
  47. /package/dist/{chunk-2XS2PM62.js.map → chunk-OC6S4XFL.js.map} +0 -0
  48. /package/dist/{chunk-DP3YEVSX.js.map → chunk-WILXD5X3.js.map} +0 -0
  49. /package/dist/{chunk-ZGQ7Q4ZU.js.map → chunk-WM25QE7E.js.map} +0 -0
  50. /package/dist/{chunk-Z3EJX3VG.js.map → chunk-Z456IHCB.js.map} +0 -0
@@ -0,0 +1,1858 @@
1
+ import {
2
+ deepEqual,
3
+ flatten,
4
+ src_default,
5
+ unflatten
6
+ } from "./chunk-AKIRHA4Q.js";
7
+
8
+ // ../../../node_modules/.pnpm/is-what@4.1.16/node_modules/is-what/dist/index.js
9
+ function getType(payload) {
10
+ return Object.prototype.toString.call(payload).slice(8, -1);
11
+ }
12
+ function isPlainObject(payload) {
13
+ if (getType(payload) !== "Object")
14
+ return false;
15
+ const prototype = Object.getPrototypeOf(payload);
16
+ return !!prototype && prototype.constructor === Object && prototype === Object.prototype;
17
+ }
18
+ function isNull(payload) {
19
+ return getType(payload) === "Null";
20
+ }
21
+ function isOneOf(a, b, c, d, e) {
22
+ return (value) => a(value) || b(value) || !!c && c(value) || !!d && d(value) || !!e && e(value);
23
+ }
24
+ function isUndefined(payload) {
25
+ return getType(payload) === "Undefined";
26
+ }
27
+ var isNullOrUndefined = isOneOf(isNull, isUndefined);
28
+ function isSymbol(payload) {
29
+ return getType(payload) === "Symbol";
30
+ }
31
+
32
+ // ../../../node_modules/.pnpm/merge-anything@5.1.7/node_modules/merge-anything/dist/index.js
33
+ function assignProp(carry, key, newVal, originalObject) {
34
+ const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
35
+ if (propType === "enumerable")
36
+ carry[key] = newVal;
37
+ if (propType === "nonenumerable") {
38
+ Object.defineProperty(carry, key, {
39
+ value: newVal,
40
+ enumerable: false,
41
+ writable: true,
42
+ configurable: true
43
+ });
44
+ }
45
+ }
46
+ function mergeRecursively(origin, newComer, compareFn) {
47
+ if (!isPlainObject(newComer))
48
+ return newComer;
49
+ let newObject = {};
50
+ if (isPlainObject(origin)) {
51
+ const props2 = Object.getOwnPropertyNames(origin);
52
+ const symbols2 = Object.getOwnPropertySymbols(origin);
53
+ newObject = [...props2, ...symbols2].reduce((carry, key) => {
54
+ const targetVal = origin[key];
55
+ if (!isSymbol(key) && !Object.getOwnPropertyNames(newComer).includes(key) || isSymbol(key) && !Object.getOwnPropertySymbols(newComer).includes(key)) {
56
+ assignProp(
57
+ carry,
58
+ key,
59
+ targetVal,
60
+ origin
61
+ );
62
+ }
63
+ return carry;
64
+ }, {});
65
+ }
66
+ const props = Object.getOwnPropertyNames(newComer);
67
+ const symbols = Object.getOwnPropertySymbols(newComer);
68
+ const result = [...props, ...symbols].reduce((carry, key) => {
69
+ let newVal = newComer[key];
70
+ const targetVal = isPlainObject(origin) ? origin[key] : void 0;
71
+ if (targetVal !== void 0 && isPlainObject(newVal)) {
72
+ newVal = mergeRecursively(targetVal, newVal, compareFn);
73
+ }
74
+ const propToAssign = compareFn ? compareFn(targetVal, newVal, key) : newVal;
75
+ assignProp(
76
+ carry,
77
+ key,
78
+ propToAssign,
79
+ newComer
80
+ );
81
+ return carry;
82
+ }, newObject);
83
+ return result;
84
+ }
85
+ function merge(object, ...otherObjects) {
86
+ return otherObjects.reduce((result, newComer) => {
87
+ return mergeRecursively(result, newComer);
88
+ }, object);
89
+ }
90
+
91
+ // ../../../node_modules/.pnpm/@supabase-cache-helpers+postgrest-core@0.12.3_patch_hash=pk7qqc22n5ajzpk5ax7g6nuane_@supabase+postgrest-js@2.81.1/node_modules/@supabase-cache-helpers/postgrest-core/dist/index.js
92
+ var __defProp = Object.defineProperty;
93
+ var __defProps = Object.defineProperties;
94
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
95
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
96
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
97
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
98
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
99
+ var __spreadValues = (a, b) => {
100
+ for (var prop in b || (b = {}))
101
+ if (__hasOwnProp.call(b, prop))
102
+ __defNormalProp(a, prop, b[prop]);
103
+ if (__getOwnPropSymbols)
104
+ for (var prop of __getOwnPropSymbols(b)) {
105
+ if (__propIsEnum.call(b, prop))
106
+ __defNormalProp(a, prop, b[prop]);
107
+ }
108
+ return a;
109
+ };
110
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
111
+ var __async = (__this, __arguments, generator) => {
112
+ return new Promise((resolve, reject) => {
113
+ var fulfilled = (value) => {
114
+ try {
115
+ step(generator.next(value));
116
+ } catch (e) {
117
+ reject(e);
118
+ }
119
+ };
120
+ var rejected = (value) => {
121
+ try {
122
+ step(generator.throw(value));
123
+ } catch (e) {
124
+ reject(e);
125
+ }
126
+ };
127
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
128
+ step((generator = generator.apply(__this, __arguments)).next());
129
+ });
130
+ };
131
+ var isAndFilter = (f) => Array.isArray(f.and);
132
+ var isOrFilter = (f) => Array.isArray(f.or);
133
+ var isFilterDefinition = (f) => !isAndFilter(f) && !isOrFilter(f);
134
+ var extractPathsFromFilters = (f, p) => {
135
+ return f.reduce((prev, filter) => {
136
+ var _a;
137
+ if (isAndFilter(filter)) {
138
+ prev.push(...extractPathsFromFilters(filter.and, p));
139
+ } else if (isOrFilter(filter)) {
140
+ prev.push(...extractPathsFromFilters(filter.or, p));
141
+ } else if (isFilterDefinition(filter)) {
142
+ const relatedPath = p.find((p2) => p2.path === filter.path);
143
+ const pathElements = filter.path.split(".");
144
+ const aliasElements = (_a = filter.alias) == null ? void 0 : _a.split(".");
145
+ const declaration = pathElements.map(
146
+ (el, idx) => `${aliasElements && aliasElements[idx] !== el ? `${aliasElements[idx]}:` : ""}${el}`
147
+ ).join(".");
148
+ prev.push({
149
+ path: filter.path,
150
+ alias: filter.alias,
151
+ declaration: relatedPath ? relatedPath.declaration : declaration
152
+ });
153
+ }
154
+ return prev;
155
+ }, []);
156
+ };
157
+ var removeFirstPathElement = (p) => {
158
+ const aliasWithoutFirstElement = p.alias ? p.alias.split(".").slice(1).join(".") : void 0;
159
+ const pathWithoutFirstEelment = p.path.split(".").slice(1).join(".");
160
+ return {
161
+ declaration: p.declaration.split(".").slice(1).join("."),
162
+ path: pathWithoutFirstEelment,
163
+ alias: aliasWithoutFirstElement && (aliasWithoutFirstElement.split(".").length > 1 || aliasWithoutFirstElement !== pathWithoutFirstEelment) ? aliasWithoutFirstElement : void 0
164
+ };
165
+ };
166
+ var isNestedPath = (p) => Array.isArray(p.paths);
167
+ var groupPathsRecursive = (paths) => {
168
+ const grouped = paths.reduce((prev, curr) => {
169
+ const levels = curr.path.split(".").length;
170
+ if (levels === 1) {
171
+ prev.push(curr);
172
+ return prev;
173
+ }
174
+ const firstLevelDeclaration = curr.declaration.split(".")[0];
175
+ const indexOfNested = prev.findIndex(
176
+ (p) => isNestedPath(p) && p.declaration === firstLevelDeclaration
177
+ );
178
+ const pathWithoutCurrentLevel = removeFirstPathElement(curr);
179
+ if (indexOfNested !== -1) {
180
+ prev[indexOfNested].paths.push(pathWithoutCurrentLevel);
181
+ return prev;
182
+ }
183
+ prev.push(__spreadValues({
184
+ declaration: firstLevelDeclaration,
185
+ path: curr.path.split(".")[0],
186
+ paths: [pathWithoutCurrentLevel]
187
+ }, curr.alias ? { alias: curr.alias.split(".")[0] } : {}));
188
+ return prev;
189
+ }, []);
190
+ return grouped.map(
191
+ (p) => isNestedPath(p) ? __spreadProps(__spreadValues({}, p), { paths: groupPathsRecursive(p.paths) }) : p
192
+ );
193
+ };
194
+ var parseSelectParam = (s, currentPath) => {
195
+ s = s.replace(/\s/g, "");
196
+ let result;
197
+ try {
198
+ result = src_default.matchRecursive(`,${s}`, "([^,\\(]+)\\(", "\\)", "g", {
199
+ valueNames: {
200
+ "0": null,
201
+ "1": "tableName",
202
+ "2": "selectedColumns",
203
+ "3": null
204
+ }
205
+ }).map((item) => {
206
+ if (item.name === "tableName" && item.value && !item.value.startsWith(",")) {
207
+ item.value = "," + item.value;
208
+ }
209
+ return item;
210
+ });
211
+ } catch (e) {
212
+ const path = (currentPath == null ? void 0 : currentPath.path) ? `${currentPath == null ? void 0 : currentPath.declaration} with alias ${currentPath == null ? void 0 : currentPath.alias} at path ${currentPath == null ? void 0 : currentPath.path}` : "root";
213
+ throw new Error(`Unable to parse ${s} at ${path}`, {
214
+ cause: e
215
+ });
216
+ }
217
+ const foreignTables = result.reduce((prev, curr, idx, matches) => {
218
+ if (curr.name === "selectedColumns" && curr.value.length > 0) {
219
+ const name = matches[idx - 1].value.slice(1, -1);
220
+ prev = __spreadProps(__spreadValues({}, prev), { [name]: curr.value });
221
+ }
222
+ return prev;
223
+ }, {});
224
+ const columns = s.replace(
225
+ new RegExp(
226
+ `${Object.entries(foreignTables).map(
227
+ ([table, selectedColumns]) => `${table}(${selectedColumns})`.replace(/\(/g, "\\(").replace(/\)/g, "\\)").replace(/\*/g, "\\*")
228
+ ).join("|")}`,
229
+ "g"
230
+ ),
231
+ ""
232
+ ).replace(/(,)\1+/g, ",").split(",").filter((c) => c.length > 0).map((c) => {
233
+ var _a;
234
+ const split = c.split(":");
235
+ const hasAlias = split.length > 1;
236
+ const aggregateSplit = split[hasAlias ? 1 : 0].split(".");
237
+ const hasAggregate = aggregateSplit.length > 1 && aggregateSplit[1].endsWith("()");
238
+ return __spreadValues({
239
+ declaration: [currentPath == null ? void 0 : currentPath.declaration, c].filter(Boolean).join("."),
240
+ alias: hasAlias || (currentPath == null ? void 0 : currentPath.alias) ? [(_a = currentPath == null ? void 0 : currentPath.alias) != null ? _a : currentPath == null ? void 0 : currentPath.path, split[0]].filter(Boolean).join(".") : void 0,
241
+ path: [
242
+ currentPath == null ? void 0 : currentPath.path,
243
+ hasAggregate ? aggregateSplit[0] : split[hasAlias ? 1 : 0]
244
+ ].filter(Boolean).join(".")
245
+ }, hasAggregate ? { aggregate: aggregateSplit[1].slice(0, -2) } : {});
246
+ });
247
+ return [
248
+ ...columns,
249
+ ...Object.entries(foreignTables).flatMap(
250
+ ([currentDeclaration, selectedColumns]) => {
251
+ var _a;
252
+ const aliasSplit = currentDeclaration.split(":");
253
+ const currentAliasElem = aliasSplit.length > 1 ? aliasSplit[0] : void 0;
254
+ const currentPathDeclaration = aliasSplit[aliasSplit.length - 1];
255
+ const currentPathElem = currentPathDeclaration.split("!")[0];
256
+ const path = [currentPath == null ? void 0 : currentPath.path, currentPathElem].filter(Boolean).join(".");
257
+ const alias = [
258
+ (_a = currentPath == null ? void 0 : currentPath.alias) != null ? _a : currentPath == null ? void 0 : currentPath.path,
259
+ currentAliasElem != null ? currentAliasElem : currentPathElem
260
+ ].filter(Boolean).join(".");
261
+ const declaration = [currentPath == null ? void 0 : currentPath.declaration, currentDeclaration].filter(Boolean).join(".");
262
+ return parseSelectParam(`${selectedColumns}`, {
263
+ path,
264
+ alias: (currentPath == null ? void 0 : currentPath.alias) || currentAliasElem ? alias : void 0,
265
+ declaration
266
+ });
267
+ }
268
+ )
269
+ ];
270
+ };
271
+ var removeAliasFromDeclaration = (d) => d.split(".").map((el) => el.split(":").pop()).join(".");
272
+ var buildSelectStatement = (paths) => {
273
+ return buildSelectStatementFromGroupedPaths(groupPathsRecursive(paths));
274
+ };
275
+ var buildSelectStatementFromGroupedPaths = (paths) => paths.map((i) => {
276
+ if (isNestedPath(i)) {
277
+ return `${i.declaration}(${buildSelectStatement(i.paths)})`;
278
+ }
279
+ return `${i.alias ? `${i.alias}:` : ""}${i.path}`;
280
+ }).join(",");
281
+ var DEDUPE_ALIAS_PREFIX = "d";
282
+ var dedupeGroupedPathsRecursive = (grouped) => {
283
+ const dedupeCounters = /* @__PURE__ */ new Map();
284
+ return grouped.map((p, idx, a) => {
285
+ if (!isNestedPath(p)) return p;
286
+ if (a.some((i, itemIdx) => i.path === p.path && idx !== itemIdx)) {
287
+ const counter = dedupeCounters.get(p.path) || 0;
288
+ dedupeCounters.set(p.path, counter + 1);
289
+ const alias = [DEDUPE_ALIAS_PREFIX, counter, p.path].join("_");
290
+ return __spreadProps(__spreadValues({}, p), {
291
+ alias,
292
+ declaration: `${alias}:${p.declaration}`,
293
+ paths: dedupeGroupedPathsRecursive(p.paths)
294
+ });
295
+ }
296
+ return __spreadProps(__spreadValues({}, p), {
297
+ paths: dedupeGroupedPathsRecursive(p.paths)
298
+ });
299
+ });
300
+ };
301
+ var buildNormalizedQuery = ({
302
+ query,
303
+ disabled,
304
+ queriesForTable
305
+ }) => {
306
+ var _a;
307
+ const userQueryPaths = query ? parseSelectParam(query) : null;
308
+ const paths = userQueryPaths ? userQueryPaths.map((q) => ({
309
+ declaration: removeAliasFromDeclaration(q.declaration),
310
+ path: q.path
311
+ })) : [];
312
+ if (!disabled) {
313
+ for (const tableQuery of queriesForTable()) {
314
+ for (const filterPath of extractPathsFromFilters(
315
+ tableQuery.filters,
316
+ tableQuery.paths
317
+ )) {
318
+ const path = (_a = tableQuery.paths.find(
319
+ (p) => p.path === filterPath.path && p.alias === filterPath.alias
320
+ )) != null ? _a : {
321
+ path: filterPath.path,
322
+ declaration: filterPath.path
323
+ };
324
+ if (paths.every(
325
+ (p) => removeAliasFromDeclaration(p.declaration) !== removeAliasFromDeclaration(path.declaration)
326
+ )) {
327
+ paths.push({
328
+ path: path.path,
329
+ declaration: removeAliasFromDeclaration(path.declaration)
330
+ });
331
+ }
332
+ }
333
+ for (const path of tableQuery.paths) {
334
+ if (paths.every(
335
+ (p) => removeAliasFromDeclaration(p.declaration) !== removeAliasFromDeclaration(path.declaration)
336
+ ) && // do not add agg functions
337
+ !path.declaration.endsWith(".count") && // do not add wildcard queries
338
+ !path.declaration.endsWith("*")) {
339
+ paths.push({
340
+ path: path.path,
341
+ declaration: removeAliasFromDeclaration(path.declaration)
342
+ });
343
+ }
344
+ }
345
+ }
346
+ }
347
+ const groupedPaths = groupPathsRecursive(paths);
348
+ const groupedDedupedPaths = dedupeGroupedPathsRecursive(groupedPaths);
349
+ const selectQuery = buildSelectStatementFromGroupedPaths(groupedDedupedPaths);
350
+ if (selectQuery.length === 0) return null;
351
+ return {
352
+ selectQuery,
353
+ groupedUserQueryPaths: userQueryPaths ? groupPathsRecursive(userQueryPaths) : null,
354
+ groupedPaths: groupedDedupedPaths
355
+ };
356
+ };
357
+ var get = (obj, path, defaultValue = void 0) => {
358
+ const split = path.split(/((?:\.|,|\[|\]|->>|->)+)/g);
359
+ let result = obj;
360
+ for (let i = -1; i < split.length; i += 2) {
361
+ const separator = split[i];
362
+ let key = split[i + 1];
363
+ if (!key) {
364
+ continue;
365
+ }
366
+ if ((separator == null ? void 0 : separator.endsWith("->")) || (separator == null ? void 0 : separator.endsWith("->>"))) {
367
+ if (/^\d+$/.test(key)) {
368
+ key = Number.parseInt(key, 10);
369
+ }
370
+ }
371
+ if (separator == null ? void 0 : separator.endsWith("->>")) {
372
+ result = `${result ? result[key] : result}`;
373
+ } else {
374
+ result = result ? result[key] : result;
375
+ }
376
+ }
377
+ return result === void 0 || result === obj ? defaultValue : result;
378
+ };
379
+ function isPlainObject2(value) {
380
+ return Object.prototype.toString.call(value) === "[object Object]";
381
+ }
382
+ var buildMutationFetcherResponse = (input, {
383
+ groupedPaths,
384
+ groupedUserQueryPaths
385
+ }) => {
386
+ return {
387
+ normalizedData: normalizeResponse(groupedPaths, input),
388
+ userQueryData: groupedUserQueryPaths ? buildUserQueryData(groupedUserQueryPaths, groupedPaths, input) : void 0
389
+ };
390
+ };
391
+ var normalizeResponse = (groups, obj) => {
392
+ if (groups.some((p) => p.path === "*")) {
393
+ Object.entries(obj).forEach(([k, v]) => {
394
+ if (typeof v === "object" || Array.isArray(v)) {
395
+ if (!groups.some((g) => isNestedPath(g) && g.path === k)) {
396
+ groups.push({
397
+ path: k,
398
+ declaration: k
399
+ });
400
+ }
401
+ } else if (!groups.some((g) => g.path === k)) {
402
+ groups.push({
403
+ path: k,
404
+ declaration: k
405
+ });
406
+ }
407
+ });
408
+ }
409
+ return groups.reduce((prev, curr) => {
410
+ var _a, _b;
411
+ const value = get(obj, curr.alias || curr.path);
412
+ if (typeof value === "undefined") return prev;
413
+ if (value === null) {
414
+ return __spreadProps(__spreadValues({}, prev), {
415
+ // add hint to path if it has dedupe alias
416
+ // can happen if the same relation is queried multiple times via different fkeys
417
+ [`${curr.path}${((_a = curr.alias) == null ? void 0 : _a.startsWith("d_")) && curr.declaration.split("!").length > 1 ? `!${curr.declaration.split("!")[1]}` : ""}`]: value
418
+ });
419
+ }
420
+ if (!isNestedPath(curr)) {
421
+ return __spreadValues(__spreadValues({}, prev), flatten({
422
+ [curr.path]: value !== null && (isPlainObject2(value) || Array.isArray(value) && value.length > 0) ? flatten(value) : value
423
+ }));
424
+ }
425
+ if (Array.isArray(value)) {
426
+ return __spreadValues(__spreadValues({}, prev), flatten({
427
+ [curr.path]: value.map((v) => normalizeResponse(curr.paths, v))
428
+ }));
429
+ }
430
+ return __spreadValues(__spreadValues({}, prev), flatten({
431
+ // add hint to path if it has dedupe alias
432
+ // can happen if the same relation is queried multiple times via different fkeys
433
+ [`${curr.path}${((_b = curr.alias) == null ? void 0 : _b.startsWith("d_")) && curr.declaration.split("!").length > 1 ? `!${curr.declaration.split("!")[1]}` : ""}`]: normalizeResponse(curr.paths, value)
434
+ }));
435
+ }, {});
436
+ };
437
+ var buildUserQueryData = (userQueryGroups, pathGroups, obj) => {
438
+ if (pathGroups.some((p) => p.path === "*")) {
439
+ Object.entries(obj).forEach(([k, v]) => {
440
+ if (typeof v === "object" || Array.isArray(v)) {
441
+ if (!pathGroups.some((g) => isNestedPath(g) && g.path === k)) {
442
+ pathGroups.push({
443
+ path: k,
444
+ declaration: k
445
+ });
446
+ }
447
+ } else if (!pathGroups.some((g) => g.path === k)) {
448
+ pathGroups.push({
449
+ path: k,
450
+ declaration: k
451
+ });
452
+ }
453
+ });
454
+ }
455
+ if (userQueryGroups.some((p) => p.path === "*")) {
456
+ Object.entries(obj).forEach(([k, v]) => {
457
+ if (typeof v === "object" || Array.isArray(v)) {
458
+ if (!pathGroups.some((g) => isNestedPath(g) && g.path === k)) {
459
+ userQueryGroups.push({
460
+ path: k,
461
+ declaration: k
462
+ });
463
+ }
464
+ } else if (!userQueryGroups.some((g) => g.path === k)) {
465
+ userQueryGroups.push({
466
+ path: k,
467
+ declaration: k
468
+ });
469
+ }
470
+ });
471
+ }
472
+ return userQueryGroups.reduce((prev, curr) => {
473
+ if (curr.path === "*") return prev;
474
+ const inputPath = pathGroups.find(
475
+ (p) => p.path === curr.path && isNestedPath(p) === isNestedPath(curr)
476
+ );
477
+ if (!inputPath) {
478
+ throw new Error(`Path ${curr.path} not found in response paths`);
479
+ }
480
+ const value = get(obj, inputPath.alias || inputPath.path);
481
+ if (typeof value === "undefined") return prev;
482
+ if (value === null || !isNestedPath(curr) || !isNestedPath(inputPath)) {
483
+ prev[curr.alias ? curr.alias : curr.path] = value;
484
+ } else if (Array.isArray(value)) {
485
+ prev[curr.alias ? curr.alias : curr.path] = value.map((v) => buildUserQueryData(curr.paths, inputPath.paths, v));
486
+ } else {
487
+ prev[curr.alias ? curr.alias : curr.path] = buildUserQueryData(
488
+ curr.paths,
489
+ inputPath.paths,
490
+ value
491
+ );
492
+ }
493
+ return prev;
494
+ }, {});
495
+ };
496
+ var getTableFromUrl = (url) => {
497
+ var _a;
498
+ const split = url.toString().split("/");
499
+ const table = (_a = split.pop()) == null ? void 0 : _a.split("?").shift();
500
+ const maybeRpc = split.pop();
501
+ return [maybeRpc === "rpc" ? maybeRpc : null, table].filter(Boolean).join("/");
502
+ };
503
+ var isLikeQueryBuilder = (v) => {
504
+ if (typeof v !== "object" || v === null) return false;
505
+ const obj = v;
506
+ return typeof obj["url"] === "object";
507
+ };
508
+ var getTable = (query) => {
509
+ if (!isLikeQueryBuilder(query)) {
510
+ throw new Error("Invalid PostgrestBuilder");
511
+ }
512
+ return getTableFromUrl(query["url"].pathname);
513
+ };
514
+ var isPostgrestPaginationCacheData = (q) => {
515
+ if (!Array.isArray(q)) return false;
516
+ return q.length === 0 || Array.isArray(q[0]);
517
+ };
518
+ var isPostgrestHasMorePaginationCacheData = (q) => {
519
+ if (!Array.isArray(q)) return false;
520
+ if (q.length === 0) return true;
521
+ const firstPage = q[0];
522
+ return Array.isArray(
523
+ firstPage.data
524
+ ) && typeof firstPage.hasMore === "boolean";
525
+ };
526
+ var isAnyPostgrestResponse = (q) => {
527
+ if (!q) return false;
528
+ return typeof q.data === "object" || Array.isArray(q.data);
529
+ };
530
+ var sortSearchParams = (params) => new URLSearchParams(
531
+ Array.from(params.entries()).sort((a, b) => {
532
+ const x = `${a[0]}${a[1]}`;
533
+ const y = `${b[0]}${b[1]}`;
534
+ return x > y ? 1 : -1;
535
+ })
536
+ );
537
+ var encodeObject = (obj) => {
538
+ const sortedEntries = Object.entries(
539
+ flatten(obj)
540
+ ).sort(([a], [b]) => a.length - b.length);
541
+ const bodyParams = new URLSearchParams();
542
+ sortedEntries.forEach(([key, value]) => {
543
+ bodyParams.append(key, String(value));
544
+ });
545
+ return sortSearchParams(bodyParams).toString();
546
+ };
547
+ var isPostgrestBuilder = (q) => {
548
+ return typeof q.throwOnError === "function";
549
+ };
550
+ var isPostgrestTransformBuilder = (q) => {
551
+ return typeof q.abortSignal === "function";
552
+ };
553
+ var isISODateString = (v) => typeof v === "string" && /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/.test(
554
+ v
555
+ );
556
+ var parseValue = (v) => {
557
+ if (isISODateString(v)) return new Date(v);
558
+ try {
559
+ return JSON.parse(v);
560
+ } catch (e) {
561
+ return v;
562
+ }
563
+ };
564
+ var parseOrderByKey = (v) => {
565
+ return v.split("|").map((orderBy) => {
566
+ const [tableDef, orderDef] = orderBy.split(":");
567
+ const [foreignTableOrCol, maybeCol] = tableDef.split(".");
568
+ const [dir, nulls] = orderDef.split(".");
569
+ return {
570
+ ascending: dir === "asc",
571
+ nullsFirst: nulls === "nullsFirst",
572
+ foreignTable: maybeCol ? foreignTableOrCol : void 0,
573
+ column: maybeCol ? maybeCol : foreignTableOrCol
574
+ };
575
+ });
576
+ };
577
+ var parseOrderBy = (searchParams) => {
578
+ const orderBy = [];
579
+ searchParams.forEach((value, key) => {
580
+ const split = key.split(".");
581
+ if (split[split.length === 2 ? 1 : 0] === "order") {
582
+ const orderByDefs = value.split(",");
583
+ orderByDefs.forEach((def) => {
584
+ const [column, ascending, nullsFirst] = def.split(".");
585
+ orderBy.push({
586
+ ascending: ascending === "asc",
587
+ column,
588
+ nullsFirst: nullsFirst === "nullsfirst",
589
+ foreignTable: split.length === 2 ? split[0] : void 0
590
+ });
591
+ });
592
+ }
593
+ });
594
+ return orderBy;
595
+ };
596
+ var buildDeleteFetcher = (qb, primaryKeys, opts) => (input) => __async(void 0, null, function* () {
597
+ let filterBuilder = qb.delete(opts);
598
+ if (primaryKeys.length === 1) {
599
+ const primaryKey = primaryKeys[0];
600
+ filterBuilder.in(
601
+ primaryKey,
602
+ input.map((i) => {
603
+ const v = i[primaryKey];
604
+ if (!v) {
605
+ throw new Error(
606
+ `Missing value for primary key ${primaryKey}`
607
+ );
608
+ }
609
+ return v;
610
+ })
611
+ );
612
+ } else {
613
+ filterBuilder = filterBuilder.or(
614
+ input.map(
615
+ (i) => `and(${primaryKeys.map((c) => {
616
+ const v = i[c];
617
+ if (!v) {
618
+ throw new Error(
619
+ `Missing value for primary key ${c}`
620
+ );
621
+ }
622
+ return `${c}.eq.${v}`;
623
+ })})`
624
+ ).join(",")
625
+ );
626
+ }
627
+ const primaryKeysData = input.map(
628
+ (i) => primaryKeys.reduce((prev, key) => {
629
+ return __spreadProps(__spreadValues({}, prev), {
630
+ [key]: i[key]
631
+ });
632
+ }, {})
633
+ );
634
+ const query = buildNormalizedQuery(opts);
635
+ if (query) {
636
+ const { selectQuery, groupedUserQueryPaths, groupedPaths } = query;
637
+ const groupedPathsWithPrimaryKeys = groupedPaths;
638
+ const addKeys = [];
639
+ primaryKeys.forEach((key) => {
640
+ if (!groupedPathsWithPrimaryKeys.find((p) => p.path === key)) {
641
+ groupedPathsWithPrimaryKeys.push({
642
+ declaration: key,
643
+ path: key
644
+ });
645
+ addKeys.push(key);
646
+ }
647
+ });
648
+ const { data } = yield filterBuilder.select([selectQuery, ...addKeys].join(",")).throwOnError();
649
+ return data.map(
650
+ (d) => buildMutationFetcherResponse(d, {
651
+ groupedPaths: groupedPathsWithPrimaryKeys,
652
+ groupedUserQueryPaths
653
+ })
654
+ );
655
+ }
656
+ yield filterBuilder.throwOnError();
657
+ if (opts.queriesForTable().length > 0) {
658
+ return primaryKeysData.map((pk) => ({ normalizedData: pk }));
659
+ }
660
+ return null;
661
+ });
662
+ var shouldRevalidateRelation = (relations, {
663
+ input,
664
+ getPostgrestFilter,
665
+ decodedKey: { schema, table, queryKey }
666
+ }) => Boolean(
667
+ relations.find(
668
+ (r) => (!r.schema || r.schema === schema) && r.relation === table && typeof input[r.fKeyColumn] !== "undefined" && getPostgrestFilter(queryKey, {
669
+ exclusivePaths: [r.relationIdColumn]
670
+ }).applyFilters({
671
+ [r.relationIdColumn]: input[r.fKeyColumn]
672
+ })
673
+ )
674
+ );
675
+ var shouldRevalidateTable = (tables, { decodedKey: { schema, table } }) => Boolean(
676
+ tables.find((t) => (!t.schema || t.schema === schema) && t.table === table)
677
+ );
678
+ var toHasMorePaginationCacheData = (a, currentData, chunkSize) => {
679
+ const hasMoreCache = currentData.map((p) => p.hasMore);
680
+ return a.reduce(
681
+ (resultArray, item, index) => {
682
+ var _a, _b;
683
+ const chunkIndex = Math.floor(index / chunkSize);
684
+ if (!resultArray[chunkIndex]) {
685
+ let hasMore = hasMoreCache[chunkIndex];
686
+ if (!hasMore) {
687
+ hasMore = hasMoreCache[hasMoreCache.length - 1];
688
+ }
689
+ if (chunkIndex > 0) {
690
+ resultArray[chunkIndex - 1].hasMore = true;
691
+ }
692
+ resultArray[chunkIndex] = {
693
+ data: [],
694
+ hasMore: (_b = (_a = hasMoreCache[chunkIndex]) != null ? _a : hasMoreCache[hasMoreCache.length - 1]) != null ? _b : false
695
+ };
696
+ }
697
+ resultArray[chunkIndex].data.push(item);
698
+ return resultArray;
699
+ },
700
+ []
701
+ );
702
+ };
703
+ var toPaginationCacheData = (a, chunkSize) => {
704
+ return a.reduce(
705
+ (resultArray, item, index) => {
706
+ const chunkIndex = Math.floor(index / chunkSize);
707
+ if (!resultArray[chunkIndex]) {
708
+ resultArray[chunkIndex] = [];
709
+ }
710
+ resultArray[chunkIndex].push(item);
711
+ return resultArray;
712
+ },
713
+ []
714
+ );
715
+ };
716
+ var filterByPks = (input, currentData, primaryKeys) => {
717
+ return currentData.filter(
718
+ (i) => primaryKeys.some((pk) => i[pk] !== input[pk])
719
+ );
720
+ };
721
+ var deleteItem = (op, cache) => __async(void 0, null, function* () {
722
+ var _a;
723
+ const {
724
+ revalidateRelations: revalidateRelationsOpt,
725
+ revalidateTables: revalidateTablesOpt,
726
+ schema,
727
+ table
728
+ } = op;
729
+ const { cacheKeys, decode: decode2, getPostgrestFilter, mutate, revalidate } = cache;
730
+ const mutations = [];
731
+ for (const k of cacheKeys) {
732
+ const key = decode2(k);
733
+ if (!key) continue;
734
+ const filter = getPostgrestFilter(key.queryKey);
735
+ if (key.schema === schema && key.table === table) {
736
+ if (key.isHead === true) {
737
+ mutations.push(revalidate(k));
738
+ } else {
739
+ const transformedInput = filter.denormalize(op.input);
740
+ if (
741
+ // For delete, the input has to have a value for all primary keys
742
+ op.primaryKeys.every(
743
+ (pk) => typeof transformedInput[pk] !== "undefined"
744
+ )
745
+ ) {
746
+ const limit = (_a = key.limit) != null ? _a : 1e3;
747
+ mutations.push(
748
+ mutate(k, (currentData) => {
749
+ if (!currentData) return currentData;
750
+ if (isPostgrestHasMorePaginationCacheData(currentData)) {
751
+ return toHasMorePaginationCacheData(
752
+ filterByPks(
753
+ transformedInput,
754
+ currentData.flatMap((p) => p.data),
755
+ op.primaryKeys
756
+ ),
757
+ currentData,
758
+ limit
759
+ );
760
+ } else if (isPostgrestPaginationCacheData(currentData)) {
761
+ return toPaginationCacheData(
762
+ filterByPks(
763
+ transformedInput,
764
+ currentData.flat(),
765
+ op.primaryKeys
766
+ ),
767
+ limit
768
+ );
769
+ } else if (isAnyPostgrestResponse(currentData)) {
770
+ const { data } = currentData;
771
+ if (!Array.isArray(data)) {
772
+ if (data && op.primaryKeys.some(
773
+ (pk) => transformedInput[pk] !== data[pk]
774
+ )) {
775
+ return currentData;
776
+ } else {
777
+ return { data: null };
778
+ }
779
+ }
780
+ const newData = filterByPks(
781
+ transformedInput,
782
+ data,
783
+ op.primaryKeys
784
+ );
785
+ return {
786
+ data: newData,
787
+ count: newData.length
788
+ };
789
+ }
790
+ })
791
+ );
792
+ }
793
+ }
794
+ }
795
+ if (revalidateTablesOpt && shouldRevalidateTable(revalidateTablesOpt, { decodedKey: key })) {
796
+ mutations.push(revalidate(k));
797
+ }
798
+ if (revalidateRelationsOpt && shouldRevalidateRelation(revalidateRelationsOpt, {
799
+ input: op.input,
800
+ getPostgrestFilter,
801
+ decodedKey: key
802
+ })) {
803
+ mutations.push(revalidate(k));
804
+ }
805
+ }
806
+ yield Promise.all(mutations);
807
+ });
808
+ function buildInsertFetcher(qb, opts) {
809
+ return (input) => __async(this, null, function* () {
810
+ const query = buildNormalizedQuery(opts);
811
+ if (query) {
812
+ const { selectQuery, groupedUserQueryPaths, groupedPaths } = query;
813
+ const { data } = yield qb.insert(input, opts).select(selectQuery).throwOnError();
814
+ return data.map(
815
+ (d) => buildMutationFetcherResponse(d, {
816
+ groupedUserQueryPaths,
817
+ groupedPaths
818
+ })
819
+ );
820
+ }
821
+ yield qb.insert(input).throwOnError();
822
+ return input.map((d) => ({ normalizedData: d }));
823
+ });
824
+ }
825
+ function binarySearch(arr, el, compare) {
826
+ let m = 0;
827
+ let n = arr.length - 1;
828
+ while (m <= n) {
829
+ const k = n + m >> 1;
830
+ const cmp = compare(el, arr[k]);
831
+ if (cmp > 0) {
832
+ m = k + 1;
833
+ } else if (cmp < 0) {
834
+ n = k - 1;
835
+ } else {
836
+ return k;
837
+ }
838
+ }
839
+ return m;
840
+ }
841
+ var ifDateGetTime = (v) => {
842
+ if (v instanceof Date) return v.getTime();
843
+ if (typeof v === "string") {
844
+ const t = new Date(v).getTime();
845
+ if (!isNaN(t)) return t;
846
+ }
847
+ return v;
848
+ };
849
+ var buildSortedComparator = (orderBy) => {
850
+ return (a, b) => {
851
+ for (const { column, ascending, nullsFirst, foreignTable } of orderBy) {
852
+ const aValue = ifDateGetTime(
853
+ get(
854
+ a,
855
+ `${foreignTable ? `${foreignTable}.` : ""}${column}`,
856
+ null
857
+ )
858
+ );
859
+ const bValue = ifDateGetTime(
860
+ get(
861
+ b,
862
+ `${foreignTable ? `${foreignTable}.` : ""}${column}`,
863
+ null
864
+ )
865
+ );
866
+ if (aValue === bValue) continue;
867
+ if (aValue === null || aValue === void 0) {
868
+ return nullsFirst ? -1 : 1;
869
+ }
870
+ if (bValue === null || bValue === void 0) {
871
+ return nullsFirst ? 1 : -1;
872
+ }
873
+ if (ascending) {
874
+ return aValue < bValue ? -1 : 1;
875
+ }
876
+ return aValue < bValue ? 1 : -1;
877
+ }
878
+ return 0;
879
+ };
880
+ };
881
+ var findIndexOrdered = (input, currentData, orderBy) => binarySearch(currentData, input, buildSortedComparator(orderBy));
882
+ var denormalize = (paths, obj) => {
883
+ const groups = groupPathsRecursive(paths);
884
+ if (groups.some((g) => g.path === "*")) {
885
+ Object.keys(obj).forEach((k) => {
886
+ const keyParts = k.split(".");
887
+ if (keyParts.length > 1 && groups.some((g) => isNestedPath(g) && g.path === keyParts[0])) {
888
+ return;
889
+ }
890
+ if (groups.some((g) => g.path === keyParts[0])) {
891
+ return;
892
+ }
893
+ groups.push({
894
+ declaration: keyParts[0],
895
+ path: keyParts[0]
896
+ });
897
+ });
898
+ }
899
+ return groups.reduce((prev, curr) => {
900
+ if (curr.path === "*") return prev;
901
+ let value = obj[curr.path];
902
+ if (!isNestedPath(curr)) {
903
+ if (typeof value === "undefined") {
904
+ const array = Object.entries(obj).reduce((prev2, [k, v]) => {
905
+ if (new RegExp(`^${curr.path}.\\d+$`).test(k)) {
906
+ prev2.push(v);
907
+ }
908
+ return prev2;
909
+ }, []);
910
+ if (array.length > 0) {
911
+ value = array;
912
+ }
913
+ }
914
+ if (typeof value === "undefined") {
915
+ let isArray22 = false;
916
+ const jsonValue = Object.entries(obj).reduce(
917
+ (prev2, [k, v]) => {
918
+ if (k.startsWith(`${curr.path}.`)) {
919
+ const key = k.slice(curr.path.length + 1);
920
+ const maybeIdx = key.match(/^\b\d+\b/);
921
+ if (maybeIdx && isFlatNestedArray(prev2)) {
922
+ isArray22 = true;
923
+ prev2 = __spreadProps(__spreadValues({}, prev2), {
924
+ [maybeIdx[0]]: __spreadProps(__spreadValues({}, prev2[maybeIdx[0]] ? prev2[maybeIdx[0]] : {}), {
925
+ [key.slice(maybeIdx[0].length + 1)]: v
926
+ })
927
+ });
928
+ } else {
929
+ prev2[maybeIdx ? maybeIdx[0] : key] = v;
930
+ }
931
+ }
932
+ return prev2;
933
+ },
934
+ {}
935
+ );
936
+ if (Object.keys(jsonValue).length > 0) {
937
+ if (isArray22) {
938
+ value = Object.values(jsonValue).map((v) => unflatten(v));
939
+ } else {
940
+ value = unflatten(jsonValue);
941
+ }
942
+ }
943
+ }
944
+ if (typeof value === "undefined") {
945
+ return prev;
946
+ }
947
+ return __spreadProps(__spreadValues({}, prev), {
948
+ [curr.alias || curr.path]: value
949
+ });
950
+ }
951
+ if (value === null || Array.isArray(value) && value.length === 0) {
952
+ return __spreadProps(__spreadValues({}, prev), {
953
+ [curr.alias || curr.path]: value
954
+ });
955
+ }
956
+ let isArray2 = false;
957
+ const flatNestedObjectOrArray = Object.entries(obj).reduce((prev2, [k, v]) => {
958
+ const isNested = k.startsWith(`${curr.path}.`) || k.includes("!") && k.startsWith(`${removeFirstAlias(curr.declaration)}.`);
959
+ if (!isNested) return prev2;
960
+ const flatKey = k.slice(
961
+ (k.includes("!") ? removeFirstAlias(curr.declaration) : curr.path).length + 1
962
+ );
963
+ const maybeIdx = flatKey.match(/^\b\d+\b/);
964
+ if (maybeIdx && isFlatNestedArray(prev2)) {
965
+ isArray2 = true;
966
+ const key = flatKey.slice(maybeIdx[0].length + 1);
967
+ return __spreadProps(__spreadValues({}, prev2), {
968
+ [maybeIdx[0]]: __spreadProps(__spreadValues({}, prev2[maybeIdx[0]] ? prev2[maybeIdx[0]] : {}), {
969
+ [key]: v
970
+ })
971
+ });
972
+ }
973
+ return __spreadProps(__spreadValues({}, prev2), {
974
+ [flatKey]: v
975
+ });
976
+ }, {});
977
+ if (Object.keys(flatNestedObjectOrArray).length === 0) return prev;
978
+ if (isArray2 && isFlatNestedArray(flatNestedObjectOrArray)) {
979
+ return __spreadProps(__spreadValues({}, prev), {
980
+ [curr.alias || curr.path]: Object.values(flatNestedObjectOrArray).map(
981
+ (v) => denormalize(curr.paths, v)
982
+ )
983
+ });
984
+ }
985
+ return __spreadProps(__spreadValues({}, prev), {
986
+ [curr.alias || curr.path]: denormalize(
987
+ curr.paths,
988
+ flatNestedObjectOrArray
989
+ )
990
+ });
991
+ }, {});
992
+ };
993
+ var isFlatNestedArray = (obj) => true;
994
+ var removeFirstAlias = (key) => {
995
+ const split = key.split(":");
996
+ if (split.length === 1) return key;
997
+ split.shift();
998
+ return split.join(":");
999
+ };
1000
+ var filterFilterDefinitionsByPaths = (f, paths) => {
1001
+ return f.reduce((prev, filter) => {
1002
+ if (isAndFilter(filter)) {
1003
+ const filters = filterFilterDefinitionsByPaths(filter.and, paths);
1004
+ if (filters.length > 0) {
1005
+ prev.push({ and: filters });
1006
+ }
1007
+ } else if (isOrFilter(filter)) {
1008
+ const filters = filterFilterDefinitionsByPaths(filter.or, paths);
1009
+ if (filters.length > 0) {
1010
+ prev.push({ or: filters });
1011
+ }
1012
+ } else if (isFilterDefinition(filter) && paths.includes(filter.path)) {
1013
+ prev.push(filter);
1014
+ }
1015
+ return prev;
1016
+ }, []);
1017
+ };
1018
+ var isObject = (v) => typeof v === "object" && !Array.isArray(v) && v !== null;
1019
+ var isLikePostgrestBuilder = (v) => {
1020
+ if (typeof v !== "object" || v === null) return false;
1021
+ const obj = v;
1022
+ return typeof obj["url"] === "object" && typeof obj["headers"] === "object" && typeof obj["method"] === "string";
1023
+ };
1024
+ var buildLikeRegex = (search) => new RegExp(`^${search.replace(/%/g, ".*")}$`);
1025
+ var textSearch = (c, v) => {
1026
+ const regExp = `^${v.split("&").map((v2) => v2.trim().toLowerCase()).join("|").replace(/:\*/g, ".*")}$`;
1027
+ const tokens = c.match(/'(.*?)'/g).map((t) => t.replace(/'/g, "").toLowerCase());
1028
+ return tokens.some((t) => new RegExp(regExp).test(t));
1029
+ };
1030
+ var ifDateGetTime2 = (v) => v instanceof Date ? v.getTime() : v;
1031
+ var enclose = (v, char) => {
1032
+ if (!v.startsWith(char)) v = `${char}${v}`;
1033
+ if (!v.endsWith(char)) v = `${v}${char}`;
1034
+ return v;
1035
+ };
1036
+ var OPERATOR_MAP = {
1037
+ eq: (c, v) => ifDateGetTime2(c) === ifDateGetTime2(v),
1038
+ neq: (c, v) => ifDateGetTime2(c) !== ifDateGetTime2(v),
1039
+ gt: (c, v) => c > v,
1040
+ gte: (c, v) => c >= v,
1041
+ lt: (c, v) => c < v,
1042
+ lte: (c, v) => c <= v,
1043
+ like: (c, v) => buildLikeRegex(v).test(c.toString()),
1044
+ ilike: (c, v) => buildLikeRegex(v.toLowerCase()).test(c.toString().toLowerCase()),
1045
+ is: (c, v) => c === v,
1046
+ in: (c, v) => {
1047
+ const parsedValue = v.slice(1, -1).split(",");
1048
+ return parsedValue.some((i) => i === c);
1049
+ },
1050
+ // contains
1051
+ cs: (c, v) => {
1052
+ if (!Array.isArray(c)) return false;
1053
+ if (!Array.isArray(v)) v = v.slice(1, -1).split(",");
1054
+ return v.every((i) => c.some((colVal) => deepEqual(colVal, i)));
1055
+ },
1056
+ // containedBy
1057
+ cd: (c, v) => {
1058
+ if (!Array.isArray(c)) return false;
1059
+ if (!Array.isArray(v)) v = v.slice(1, -1).split(",");
1060
+ return c.every(
1061
+ (i) => v.some((cmpVal) => deepEqual(cmpVal, i))
1062
+ );
1063
+ },
1064
+ fts: textSearch,
1065
+ plfts: (c, v) => buildLikeRegex(enclose(v.toLowerCase(), "%")).test(
1066
+ c.toString().toLowerCase()
1067
+ )
1068
+ };
1069
+ function findLastIndex(array, predicate) {
1070
+ let l = array.length;
1071
+ while (l--) {
1072
+ if (predicate(array[l], l, array)) return l;
1073
+ }
1074
+ return -1;
1075
+ }
1076
+ var isNotNull = (i) => i !== null;
1077
+ var SUPPORTED_OPERATORS = ["or", ...Object.keys(OPERATOR_MAP)];
1078
+ var PostgrestQueryParser = class {
1079
+ constructor(query, opts) {
1080
+ this.opts = opts;
1081
+ this._params = new URLSearchParams(query);
1082
+ }
1083
+ /**
1084
+ * Getter that returns the paths and their aliases that the query selects. Will do the computation only once.
1085
+ *
1086
+ * ```js
1087
+ * const p = new PostgrestParser(
1088
+ * supabaseClient.from("test")
1089
+ * .select(
1090
+ * `name,
1091
+ * city:cities (
1092
+ * test:name
1093
+ * ),
1094
+ * countries (
1095
+ * capital,
1096
+ * population,
1097
+ * some_ref (
1098
+ * test:first,
1099
+ * second
1100
+ * )
1101
+ * )`
1102
+ * );
1103
+ * console.log(p.paths);
1104
+ * // [
1105
+ * // { alias: undefined, path: "name" },
1106
+ * // { alias: "city.test", path: "cities.name" },
1107
+ * // { alias: undefined, path: "countries.capital" },
1108
+ * // { alias: undefined, path: "countries.population" },
1109
+ * // {
1110
+ * // alias: "countries.some_ref.test",
1111
+ * // path: "countries.some_ref.first",
1112
+ * // },
1113
+ * // { alias: undefined, path: "countries.some_ref.second" },
1114
+ * // ];
1115
+ * ```
1116
+ *
1117
+ * @returns an array of paths that the query selects, containing the columns and aliases
1118
+ */
1119
+ get paths() {
1120
+ if (!this._paths) {
1121
+ const select = this._params.get("select");
1122
+ this._paths = select ? parseSelectParam(select) : [];
1123
+ }
1124
+ return this._paths;
1125
+ }
1126
+ /**
1127
+ * Getter that returns the filters that this query applies in a json object.
1128
+ *
1129
+ * ```js
1130
+ * const p = new PostgrestParser(
1131
+ * supabaseClient.from("test").select('*')
1132
+ * .or("full_name.eq.20,test.neq.true,and(full_name.eq.Test Name,email.eq.test@mail.com)")
1133
+ * .eq("id", "123")
1134
+ * .contains("id", "456")
1135
+ * );
1136
+ *
1137
+ * console.log(p.filters);
1138
+ *
1139
+ * // [
1140
+ * // {
1141
+ * // or: [
1142
+ * // {
1143
+ * // path: "full_name",
1144
+ * // negate: false,
1145
+ * // operator: "eq",
1146
+ * // value: 20,
1147
+ * // },
1148
+ * // {
1149
+ * // path: "test",
1150
+ * // negate: false,
1151
+ * // operator: "neq",
1152
+ * // value: true,
1153
+ * // },
1154
+ * // {
1155
+ * // and: [
1156
+ * // {
1157
+ * // path: "full_name",
1158
+ * // negate: false,
1159
+ * // operator: "eq",
1160
+ * // value: "Test Name",
1161
+ * // },
1162
+ * // {
1163
+ * // path: "email",
1164
+ * // negate: false,
1165
+ * // operator: "eq",
1166
+ * // value: "test@mail.com",
1167
+ * // },
1168
+ * // ],
1169
+ * // },
1170
+ * // ],
1171
+ * // },
1172
+ * // {
1173
+ * // path: "id",
1174
+ * // negate: false,
1175
+ * // operator: "eq",
1176
+ * // value: 123,
1177
+ * // },
1178
+ * // {
1179
+ * // path: "id",
1180
+ * // negate: false,
1181
+ * // operator: "cs",
1182
+ * // value: 456,
1183
+ * // },
1184
+ * // ];
1185
+ * ```
1186
+ *
1187
+ * @returns a FilterDefinitions object
1188
+ */
1189
+ get filters() {
1190
+ if (!this._filters) {
1191
+ const filters = [];
1192
+ this._params.forEach((value, key) => {
1193
+ if (SUPPORTED_OPERATORS.some(
1194
+ (f) => key === f || value.split(".").includes(f)
1195
+ )) {
1196
+ const filter = this.parseFilterString(`${key}.${value}`, void 0);
1197
+ if (filter !== null) filters.push(filter);
1198
+ }
1199
+ });
1200
+ this._filters = filters;
1201
+ }
1202
+ return this._filters;
1203
+ }
1204
+ parseFilterString(filter, prefix) {
1205
+ if (filter.startsWith("and(") && filter.endsWith(")")) {
1206
+ const andFilters = filter.slice(4, -1).split(",").map((s) => this.parseFilterString(s, prefix)).filter(isNotNull);
1207
+ if (andFilters.length === 0) return null;
1208
+ else return { and: andFilters };
1209
+ }
1210
+ const split = filter.split(".");
1211
+ if ([split[0], split[1]].includes("or")) {
1212
+ let foreignTable;
1213
+ if (split[1] === "or") {
1214
+ foreignTable = split[0];
1215
+ }
1216
+ const orFilters = filter.slice(4 + (foreignTable ? foreignTable.length + 1 : 0), -1).split(",").reduce((prev, curr, idx, filters) => {
1217
+ if (curr.startsWith("and(")) {
1218
+ prev = [...prev, [curr, filters[idx + 1]].join()];
1219
+ } else if (!curr.endsWith(")")) {
1220
+ prev = [...prev, curr];
1221
+ }
1222
+ return prev;
1223
+ }, []).map((s) => this.parseFilterString(s, foreignTable)).filter(isNotNull);
1224
+ if (orFilters.length === 0) return null;
1225
+ else return { or: orFilters };
1226
+ }
1227
+ const operatorIdx = findLastIndex(
1228
+ split,
1229
+ (s) => SUPPORTED_OPERATORS.includes(s)
1230
+ );
1231
+ if (operatorIdx === -1)
1232
+ throw new Error(
1233
+ `Could not find a valid operator in ${split.join(".")}. Supported are ${SUPPORTED_OPERATORS.join(",")}.`
1234
+ );
1235
+ const negate = split[operatorIdx - 1] === "not";
1236
+ const pathOrAlias = [
1237
+ prefix,
1238
+ ...split.slice(0, negate ? operatorIdx - 1 : operatorIdx)
1239
+ ].filter(Boolean).join(".").replace(/\s/g, "");
1240
+ let path = pathOrAlias;
1241
+ let alias;
1242
+ for (const p of this.paths) {
1243
+ if (p.path === pathOrAlias) {
1244
+ alias = p.alias;
1245
+ break;
1246
+ }
1247
+ if (p.alias === pathOrAlias) {
1248
+ path = p.path;
1249
+ alias = p.alias;
1250
+ break;
1251
+ }
1252
+ }
1253
+ if (this.opts && Array.isArray(this.opts.exclusivePaths) && !this.opts.exclusivePaths.includes(path)) {
1254
+ return null;
1255
+ }
1256
+ const operator = split[operatorIdx];
1257
+ const value = split.slice(operatorIdx + 1).join(".");
1258
+ return {
1259
+ path,
1260
+ alias,
1261
+ negate,
1262
+ operator,
1263
+ value: parseValue(value)
1264
+ };
1265
+ }
1266
+ };
1267
+ var PostgrestFilter = class _PostgrestFilter {
1268
+ constructor(params) {
1269
+ this.params = params;
1270
+ this._filterPaths = extractPathsFromFilters(
1271
+ this.params.filters,
1272
+ this.params.paths
1273
+ );
1274
+ this.hasWildcardPath = this.params.paths.some(
1275
+ (p) => p.declaration.endsWith("*")
1276
+ );
1277
+ this.hasAggregatePath = this.params.paths.some((p) => Boolean(p.aggregate));
1278
+ }
1279
+ static fromQuery(query, opts) {
1280
+ const parser = new PostgrestQueryParser(query, opts);
1281
+ return new _PostgrestFilter({
1282
+ filters: parser.filters,
1283
+ paths: parser.paths
1284
+ });
1285
+ }
1286
+ static fromBuilder(fb, opts) {
1287
+ if (!isLikePostgrestBuilder(fb)) {
1288
+ throw new Error("Invalid PostgrestBuilder");
1289
+ }
1290
+ const parser = new PostgrestQueryParser(
1291
+ fb["url"].searchParams.toString(),
1292
+ opts
1293
+ );
1294
+ return new _PostgrestFilter({
1295
+ filters: parser.filters,
1296
+ paths: parser.paths
1297
+ });
1298
+ }
1299
+ denormalize(obj) {
1300
+ return denormalize([...this.params.paths, ...this._filterPaths], obj);
1301
+ }
1302
+ apply(obj) {
1303
+ if (!this._fn) {
1304
+ this._fn = (obj2) => this.applyFilters(obj2) && this.hasPaths(obj2);
1305
+ }
1306
+ return this._fn(obj);
1307
+ }
1308
+ applyFilters(obj) {
1309
+ if (!this._filtersFn) {
1310
+ const filterFns = this.params.filters.map((d) => this.buildFilterFn(d));
1311
+ this._filtersFn = (obj2) => filterFns.every((fn) => isObject(obj2) && fn(obj2));
1312
+ }
1313
+ return this._filtersFn(obj);
1314
+ }
1315
+ hasFiltersOnPaths(paths) {
1316
+ return filterFilterDefinitionsByPaths(this.params.filters, paths).length > 0;
1317
+ }
1318
+ applyFiltersOnPaths(obj, paths) {
1319
+ const filterFns = filterFilterDefinitionsByPaths(
1320
+ this.params.filters,
1321
+ paths
1322
+ ).map((d) => this.buildFilterFn(d));
1323
+ const filtersFn = (obj2) => filterFns.every((fn) => isObject(obj2) && fn(obj2));
1324
+ return filtersFn(obj);
1325
+ }
1326
+ hasPaths(obj) {
1327
+ if (!this._selectFn) {
1328
+ this._selectFn = (obj2) => this.params.paths.every(
1329
+ (p) => {
1330
+ var _a;
1331
+ return this.hasPathRecursive(obj2, (_a = p.alias) != null ? _a : p.path);
1332
+ }
1333
+ );
1334
+ }
1335
+ return this._selectFn(obj);
1336
+ }
1337
+ hasPathRecursive(obj, path) {
1338
+ if (obj === null) return true;
1339
+ const pathElements = path.replace(/->>|->/g, ".").split(".");
1340
+ if (pathElements.length === 1) {
1341
+ return typeof get(obj, pathElements[0]) !== "undefined";
1342
+ }
1343
+ const currentPathElement = pathElements.shift();
1344
+ const v = get(obj, currentPathElement);
1345
+ if (typeof v === "undefined") return false;
1346
+ if (Array.isArray(v)) {
1347
+ return v.every((i) => this.hasPathRecursive(i, pathElements.join(".")));
1348
+ }
1349
+ return this.hasPathRecursive(v, pathElements.join("."));
1350
+ }
1351
+ applyFilterFn(obj, path, {
1352
+ filterFn,
1353
+ value,
1354
+ negate
1355
+ }) {
1356
+ const pathElements = path.replace(/->>|->/g, ".").split(".");
1357
+ const v = get(obj, pathElements[0]);
1358
+ if (typeof v === "undefined") {
1359
+ if (Array.isArray(obj)) {
1360
+ return obj.every(
1361
+ (o) => this.applyFilterFn(o, path, { filterFn, value, negate })
1362
+ );
1363
+ }
1364
+ return false;
1365
+ }
1366
+ if (pathElements.length > 1) {
1367
+ return this.applyFilterFn(
1368
+ v,
1369
+ pathElements.slice(1).join("."),
1370
+ {
1371
+ filterFn,
1372
+ value,
1373
+ negate
1374
+ }
1375
+ );
1376
+ }
1377
+ const res = filterFn(parseValue(v), value);
1378
+ if (negate) return !res;
1379
+ return res;
1380
+ }
1381
+ buildFilterFn(def) {
1382
+ if ("or" in def) {
1383
+ return (obj) => def.or.some((d) => this.buildFilterFn(d)(obj));
1384
+ }
1385
+ if ("and" in def) {
1386
+ return (obj) => def.and.every((d) => this.buildFilterFn(d)(obj));
1387
+ }
1388
+ const { operator, path, value, negate, alias } = def;
1389
+ const filterFn = OPERATOR_MAP[operator];
1390
+ if (!filterFn)
1391
+ throw new Error(
1392
+ `Unable to build filter function for ${JSON.stringify(
1393
+ def
1394
+ )}. Operator ${operator} is not supported.`
1395
+ );
1396
+ return (obj) => this.applyFilterFn(obj, alias != null ? alias : path, { filterFn, value, negate });
1397
+ }
1398
+ };
1399
+ var PostgrestParser = class extends PostgrestQueryParser {
1400
+ constructor(fb, opts) {
1401
+ var _a;
1402
+ if (!isLikePostgrestBuilder(fb)) {
1403
+ throw new Error("Invalid PostgrestBuilder");
1404
+ }
1405
+ super(new URL(fb["url"]).searchParams.toString(), opts);
1406
+ this.opts = opts;
1407
+ this.orderBy = [];
1408
+ this._url = new URL(fb["url"]);
1409
+ this._headers = fb["headers"];
1410
+ this._body = isObject(fb["body"]) ? __spreadValues({}, fb["body"]) : void 0;
1411
+ this._method = fb["method"];
1412
+ this.queryKey = sortSearchParams(this._url.searchParams).toString();
1413
+ this.table = getTableFromUrl(this._url.toString());
1414
+ if (this._body) {
1415
+ this.bodyKey = encodeObject(this._body);
1416
+ }
1417
+ const preferHeaders = (this._headers["Prefer"] ?? "").split(",").reduce((prev, curr) => {
1418
+ const s = curr.split("=");
1419
+ return __spreadProps(__spreadValues({}, prev), {
1420
+ [s[0]]: s[1]
1421
+ });
1422
+ }, {});
1423
+ this.count = (_a = preferHeaders["count"]) != null ? _a : null;
1424
+ this.schema = fb["schema"];
1425
+ this.isHead = this._method === "HEAD";
1426
+ const limit = this._url.searchParams.get("limit");
1427
+ this.limit = limit ? Number(limit) : void 0;
1428
+ const offset = this._url.searchParams.get("offset");
1429
+ this.offset = offset ? Number(offset) : void 0;
1430
+ this.orderBy = parseOrderBy(this._url.searchParams);
1431
+ this.orderByKey = this.orderBy.map(
1432
+ ({ column, ascending, nullsFirst, foreignTable }) => `${foreignTable ? `${foreignTable}.` : ""}${column}:${ascending ? "asc" : "desc"}.${nullsFirst ? "nullsFirst" : "nullsLast"}`
1433
+ ).join("|");
1434
+ }
1435
+ };
1436
+ var upsert = (input, currentData, primaryKeys, filter, mergeFn, orderBy) => {
1437
+ const merge2 = mergeFn != null ? mergeFn : merge;
1438
+ const itemIdx = currentData.findIndex(
1439
+ (oldItem) => primaryKeys.every((pk) => oldItem[pk] === input[pk])
1440
+ );
1441
+ let newItem = input;
1442
+ let newItemIdx = itemIdx;
1443
+ if (itemIdx !== -1) {
1444
+ newItem = merge2(currentData[itemIdx], input);
1445
+ currentData.splice(itemIdx, 1);
1446
+ }
1447
+ if (orderBy && Array.isArray(orderBy) && orderBy.length > 0) {
1448
+ newItemIdx = findIndexOrdered(newItem, currentData, orderBy);
1449
+ }
1450
+ if (newItemIdx === -1) {
1451
+ newItemIdx = 0;
1452
+ }
1453
+ if (filter.apply(newItem)) {
1454
+ currentData.splice(newItemIdx, 0, newItem);
1455
+ }
1456
+ return currentData;
1457
+ };
1458
+ var upsertItem = (op, cache) => __async(void 0, null, function* () {
1459
+ var _a, _b;
1460
+ const {
1461
+ revalidateRelations: revalidateRelationsOpt,
1462
+ revalidateTables: revalidateTablesOpt,
1463
+ schema,
1464
+ table,
1465
+ primaryKeys
1466
+ } = op;
1467
+ const { cacheKeys, decode: decode2, getPostgrestFilter, mutate, revalidate } = cache;
1468
+ const mutations = [];
1469
+ for (const k of cacheKeys) {
1470
+ const key = decode2(k);
1471
+ if (!key) continue;
1472
+ const filter = getPostgrestFilter(key.queryKey);
1473
+ if (key.schema === schema && key.table === table) {
1474
+ const transformedInput = filter.denormalize(op.input);
1475
+ if (filter.applyFilters(transformedInput) || // also allow upsert if either the filter does not apply eq filters on any pk
1476
+ !filter.hasFiltersOnPaths(op.primaryKeys) || // or input matches all pk filters
1477
+ filter.applyFiltersOnPaths(transformedInput, op.primaryKeys)) {
1478
+ const merge2 = (_a = op.merge) != null ? _a : merge;
1479
+ const limit = (_b = key.limit) != null ? _b : 1e3;
1480
+ const orderBy = key.orderByKey ? parseOrderByKey(key.orderByKey) : void 0;
1481
+ if (key.isHead === true || filter.hasWildcardPath || filter.hasAggregatePath) {
1482
+ mutations.push(revalidate(k));
1483
+ } else {
1484
+ mutations.push(
1485
+ mutate(k, (currentData) => {
1486
+ if (!currentData) return currentData;
1487
+ if (isPostgrestHasMorePaginationCacheData(currentData)) {
1488
+ return toHasMorePaginationCacheData(
1489
+ upsert(
1490
+ transformedInput,
1491
+ currentData.flatMap((p) => p.data),
1492
+ primaryKeys,
1493
+ filter,
1494
+ merge2,
1495
+ orderBy
1496
+ ),
1497
+ currentData,
1498
+ limit
1499
+ );
1500
+ } else if (isPostgrestPaginationCacheData(currentData)) {
1501
+ return toPaginationCacheData(
1502
+ upsert(
1503
+ transformedInput,
1504
+ currentData.flat(),
1505
+ primaryKeys,
1506
+ filter,
1507
+ merge2,
1508
+ orderBy
1509
+ ),
1510
+ limit
1511
+ );
1512
+ } else if (isAnyPostgrestResponse(currentData)) {
1513
+ const { data } = currentData;
1514
+ if (!Array.isArray(data)) {
1515
+ if (data === null) {
1516
+ return {
1517
+ data,
1518
+ count: currentData.count
1519
+ };
1520
+ }
1521
+ const newData2 = merge2(data, transformedInput);
1522
+ return {
1523
+ // Check if the new data is still valid given the key
1524
+ data: filter.apply(newData2) ? newData2 : null,
1525
+ count: currentData.count
1526
+ };
1527
+ }
1528
+ const newData = upsert(
1529
+ transformedInput,
1530
+ // deep copy data to avoid mutating the original
1531
+ JSON.parse(JSON.stringify(data)),
1532
+ primaryKeys,
1533
+ filter,
1534
+ merge2,
1535
+ orderBy
1536
+ );
1537
+ return {
1538
+ data: newData,
1539
+ count: newData.length
1540
+ };
1541
+ }
1542
+ return currentData;
1543
+ })
1544
+ );
1545
+ }
1546
+ }
1547
+ }
1548
+ if (revalidateTablesOpt && shouldRevalidateTable(revalidateTablesOpt, { decodedKey: key })) {
1549
+ mutations.push(revalidate(k));
1550
+ }
1551
+ if (revalidateRelationsOpt && shouldRevalidateRelation(revalidateRelationsOpt, {
1552
+ input: op.input,
1553
+ getPostgrestFilter,
1554
+ decodedKey: key
1555
+ })) {
1556
+ mutations.push(revalidate(k));
1557
+ }
1558
+ }
1559
+ yield Promise.all(mutations);
1560
+ });
1561
+
1562
+ // ../../../node_modules/.pnpm/@supabase-cache-helpers+postgrest-react-query@1.13.6_@supabase+postgrest-js@2.81.1_@tanstack+_yc5q7qvczk7zvppefoodrwog4i/node_modules/@supabase-cache-helpers/postgrest-react-query/dist/index.js
1563
+ import { useQueryClient as useQueryClient3 } from "@tanstack/react-query";
1564
+ import { useQueryClient } from "@tanstack/react-query";
1565
+ import { useQueryClient as useQueryClient2 } from "@tanstack/react-query";
1566
+ import { useQueryClient as useQueryClient4 } from "@tanstack/react-query";
1567
+ import { useQueryClient as useQueryClient5 } from "@tanstack/react-query";
1568
+ import { useQueryClient as useQueryClient6 } from "@tanstack/react-query";
1569
+ import { useMutation } from "@tanstack/react-query";
1570
+ import { useMutation as useMutation2 } from "@tanstack/react-query";
1571
+ import { useMutation as useMutation3 } from "@tanstack/react-query";
1572
+ import { useMutation as useMutation4 } from "@tanstack/react-query";
1573
+ import { useMutation as useMutation5 } from "@tanstack/react-query";
1574
+ import {
1575
+ useQuery as useReactQuery
1576
+ } from "@tanstack/react-query";
1577
+ import {
1578
+ REALTIME_LISTEN_TYPES,
1579
+ REALTIME_POSTGRES_CHANGES_LISTEN_EVENT
1580
+ } from "@supabase/supabase-js";
1581
+ import { useEffect, useState } from "react";
1582
+ import {
1583
+ REALTIME_LISTEN_TYPES as REALTIME_LISTEN_TYPES2,
1584
+ REALTIME_POSTGRES_CHANGES_LISTEN_EVENT as REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2
1585
+ } from "@supabase/supabase-js";
1586
+ import { useEffect as useEffect2, useState as useState2 } from "react";
1587
+ var __defProp2 = Object.defineProperty;
1588
+ var __defProps2 = Object.defineProperties;
1589
+ var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors;
1590
+ var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
1591
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1592
+ var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
1593
+ var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1594
+ var __spreadValues2 = (a, b) => {
1595
+ for (var prop in b || (b = {}))
1596
+ if (__hasOwnProp2.call(b, prop))
1597
+ __defNormalProp2(a, prop, b[prop]);
1598
+ if (__getOwnPropSymbols2)
1599
+ for (var prop of __getOwnPropSymbols2(b)) {
1600
+ if (__propIsEnum2.call(b, prop))
1601
+ __defNormalProp2(a, prop, b[prop]);
1602
+ }
1603
+ return a;
1604
+ };
1605
+ var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b));
1606
+ var __async2 = (__this, __arguments, generator) => {
1607
+ return new Promise((resolve, reject) => {
1608
+ var fulfilled = (value) => {
1609
+ try {
1610
+ step(generator.next(value));
1611
+ } catch (e) {
1612
+ reject(e);
1613
+ }
1614
+ };
1615
+ var rejected = (value) => {
1616
+ try {
1617
+ step(generator.throw(value));
1618
+ } catch (e) {
1619
+ reject(e);
1620
+ }
1621
+ };
1622
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
1623
+ step((generator = generator.apply(__this, __arguments)).next());
1624
+ });
1625
+ };
1626
+ var POSTGREST_FILTER_KEY_PREFIX = "postgrest-filter";
1627
+ var usePostgrestFilterCache = () => {
1628
+ const queryClient = useQueryClient();
1629
+ return (query, opts) => {
1630
+ const key = [
1631
+ POSTGREST_FILTER_KEY_PREFIX,
1632
+ query,
1633
+ opts ? encodeObject(opts) : null
1634
+ ];
1635
+ const cacheData = queryClient.getQueryData(key);
1636
+ if (cacheData instanceof PostgrestFilter) {
1637
+ return cacheData;
1638
+ }
1639
+ const filter = PostgrestFilter.fromQuery(query, opts);
1640
+ queryClient.setQueryData(key, filter);
1641
+ return filter;
1642
+ };
1643
+ };
1644
+ var KEY_PREFIX = "postgrest";
1645
+ var INFINITE_KEY_PREFIX = "page";
1646
+ var encode = (key, isInfinite) => {
1647
+ var _a;
1648
+ if (!isPostgrestBuilder(key)) {
1649
+ throw new Error("Key is not a PostgrestBuilder");
1650
+ }
1651
+ const parser = new PostgrestParser(key);
1652
+ return [
1653
+ KEY_PREFIX,
1654
+ isInfinite ? INFINITE_KEY_PREFIX : "null",
1655
+ parser.schema,
1656
+ parser.table,
1657
+ parser.queryKey,
1658
+ (_a = parser.bodyKey) != null ? _a : "null",
1659
+ `count=${parser.count}`,
1660
+ `head=${parser.isHead}`,
1661
+ parser.orderByKey
1662
+ ];
1663
+ };
1664
+ var decode = (key) => {
1665
+ if (!Array.isArray(key)) return null;
1666
+ const [
1667
+ prefix,
1668
+ infinitePrefix,
1669
+ schema,
1670
+ table,
1671
+ queryKey,
1672
+ bodyKey,
1673
+ count,
1674
+ head,
1675
+ orderByKey
1676
+ ] = key;
1677
+ if (prefix !== KEY_PREFIX) return null;
1678
+ const params = new URLSearchParams(queryKey);
1679
+ const limit = params.get("limit");
1680
+ const offset = params.get("offset");
1681
+ const countValue = count.replace("count=", "");
1682
+ return {
1683
+ limit: limit ? Number(limit) : void 0,
1684
+ offset: offset ? Number(offset) : void 0,
1685
+ bodyKey,
1686
+ count: countValue === "null" ? null : countValue,
1687
+ isHead: head === "head=true",
1688
+ isInfinite: infinitePrefix === INFINITE_KEY_PREFIX,
1689
+ key,
1690
+ queryKey,
1691
+ schema,
1692
+ table,
1693
+ orderByKey
1694
+ };
1695
+ };
1696
+ var useQueriesForTableLoader = (table) => {
1697
+ const queryClient = useQueryClient2();
1698
+ const getPostgrestFilter = usePostgrestFilterCache();
1699
+ return () => queryClient.getQueryCache().getAll().map((c) => c.queryKey).reduce(
1700
+ (prev, curr) => {
1701
+ const decodedKey = decode(curr);
1702
+ if ((decodedKey == null ? void 0 : decodedKey.table) === table) {
1703
+ prev.push(getPostgrestFilter(decodedKey.queryKey).params);
1704
+ }
1705
+ return prev;
1706
+ },
1707
+ []
1708
+ );
1709
+ };
1710
+ function useDeleteItem(opts) {
1711
+ const queryClient = useQueryClient3();
1712
+ const getPostgrestFilter = usePostgrestFilterCache();
1713
+ return (input) => __async2(this, null, function* () {
1714
+ return yield deleteItem(
1715
+ __spreadValues2({
1716
+ input: flatten(input)
1717
+ }, opts),
1718
+ {
1719
+ cacheKeys: queryClient.getQueryCache().getAll().map((c) => c.queryKey),
1720
+ getPostgrestFilter,
1721
+ revalidate: (key) => queryClient.invalidateQueries({ queryKey: key }),
1722
+ mutate: (key, fn) => {
1723
+ queryClient.setQueriesData({ queryKey: key }, fn);
1724
+ },
1725
+ decode
1726
+ }
1727
+ );
1728
+ });
1729
+ }
1730
+ function useUpsertItem(opts) {
1731
+ const queryClient = useQueryClient6();
1732
+ const getPostgrestFilter = usePostgrestFilterCache();
1733
+ return (input) => __async2(this, null, function* () {
1734
+ return yield upsertItem(
1735
+ __spreadValues2({
1736
+ input: flatten(input)
1737
+ }, opts),
1738
+ {
1739
+ cacheKeys: queryClient.getQueryCache().getAll().map((c) => c.queryKey),
1740
+ getPostgrestFilter,
1741
+ revalidate: (key) => queryClient.invalidateQueries({ queryKey: key }),
1742
+ mutate: (key, fn) => {
1743
+ queryClient.setQueriesData({ queryKey: key }, fn);
1744
+ },
1745
+ decode
1746
+ }
1747
+ );
1748
+ });
1749
+ }
1750
+ function useDeleteManyMutation(qb, primaryKeys, query, opts) {
1751
+ const queriesForTable = useQueriesForTableLoader(getTable(qb));
1752
+ const deleteItem2 = useDeleteItem(__spreadProps2(__spreadValues2({}, opts), {
1753
+ primaryKeys,
1754
+ table: getTable(qb),
1755
+ schema: qb.schema
1756
+ }));
1757
+ return useMutation(__spreadValues2({
1758
+ mutationFn: (input) => __async2(this, null, function* () {
1759
+ const result = yield buildDeleteFetcher(
1760
+ qb,
1761
+ primaryKeys,
1762
+ __spreadValues2({
1763
+ query: query != null ? query : void 0,
1764
+ queriesForTable,
1765
+ disabled: opts == null ? void 0 : opts.disableAutoQuery
1766
+ }, opts)
1767
+ )(input);
1768
+ if (result) {
1769
+ for (const r of result) {
1770
+ deleteItem2(r.normalizedData);
1771
+ }
1772
+ }
1773
+ if (!result || result.every((r) => !r.userQueryData)) return null;
1774
+ return result.map((r) => r.userQueryData);
1775
+ })
1776
+ }, opts));
1777
+ }
1778
+ function truthy(value) {
1779
+ return !!value;
1780
+ }
1781
+ var getUserResponse = (d) => {
1782
+ if (!d) return d;
1783
+ return d.map((r) => r.userQueryData).filter(truthy);
1784
+ };
1785
+ function useInsertMutation(qb, primaryKeys, query, opts) {
1786
+ const queriesForTable = useQueriesForTableLoader(getTable(qb));
1787
+ const upsertItem2 = useUpsertItem(__spreadProps2(__spreadValues2({}, opts), {
1788
+ primaryKeys,
1789
+ table: getTable(qb),
1790
+ schema: qb.schema
1791
+ }));
1792
+ return useMutation3(__spreadValues2({
1793
+ mutationFn: (input) => __async2(this, null, function* () {
1794
+ var _a;
1795
+ const result = yield buildInsertFetcher(
1796
+ qb,
1797
+ __spreadValues2({
1798
+ query: query != null ? query : void 0,
1799
+ queriesForTable,
1800
+ disabled: opts == null ? void 0 : opts.disableAutoQuery
1801
+ }, opts)
1802
+ )(input);
1803
+ if (result) {
1804
+ yield Promise.all(
1805
+ result.map(
1806
+ (d) => __async2(this, null, function* () {
1807
+ return yield upsertItem2(d.normalizedData);
1808
+ })
1809
+ )
1810
+ );
1811
+ }
1812
+ return (_a = getUserResponse(result)) != null ? _a : null;
1813
+ })
1814
+ }, opts));
1815
+ }
1816
+ function buildQueryOpts(query, config) {
1817
+ return __spreadValues2({
1818
+ queryKey: encode(query, false),
1819
+ queryFn: (_0) => __async2(this, [_0], function* ({ signal }) {
1820
+ if (isPostgrestTransformBuilder(query)) {
1821
+ query = query.abortSignal(signal);
1822
+ }
1823
+ if (isPostgrestBuilder(query)) {
1824
+ query = query.throwOnError();
1825
+ }
1826
+ return yield query;
1827
+ })
1828
+ }, config);
1829
+ }
1830
+ function useQuery(query, config) {
1831
+ var _a, _b;
1832
+ const result = useReactQuery(
1833
+ buildQueryOpts(query, config)
1834
+ );
1835
+ if (result.isPending || result.isLoadingError) {
1836
+ return __spreadProps2(__spreadValues2({}, result), {
1837
+ data: void 0,
1838
+ count: null
1839
+ });
1840
+ }
1841
+ return __spreadProps2(__spreadValues2({}, result), {
1842
+ data: (_a = result.data) == null ? void 0 : _a.data,
1843
+ count: (_b = result.data) == null ? void 0 : _b.count
1844
+ });
1845
+ }
1846
+
1847
+ export {
1848
+ buildNormalizedQuery,
1849
+ normalizeResponse,
1850
+ encode,
1851
+ useQueriesForTableLoader,
1852
+ useDeleteItem,
1853
+ useUpsertItem,
1854
+ useDeleteManyMutation,
1855
+ useInsertMutation,
1856
+ useQuery
1857
+ };
1858
+ //# sourceMappingURL=chunk-YUX6RGLZ.js.map