@pol-studios/db 1.0.21 → 1.0.22

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 (43) hide show
  1. package/dist/auth/context.js +2 -2
  2. package/dist/auth/hooks.js +3 -3
  3. package/dist/auth/index.js +3 -3
  4. package/dist/{chunk-2T6WTCP4.js → chunk-3EVWXMUV.js} +54 -155
  5. package/dist/chunk-3EVWXMUV.js.map +1 -0
  6. package/dist/{chunk-YERWPV6B.js → chunk-3FHAKRDV.js} +145 -19
  7. package/dist/{chunk-YERWPV6B.js.map → chunk-3FHAKRDV.js.map} +1 -1
  8. package/dist/{chunk-X3HZLNBV.js → chunk-FKRACEHV.js} +2 -962
  9. package/dist/chunk-FKRACEHV.js.map +1 -0
  10. package/dist/{chunk-N26IEHZT.js → chunk-FZF26ZRB.js} +18 -2
  11. package/dist/{chunk-N26IEHZT.js.map → chunk-FZF26ZRB.js.map} +1 -1
  12. package/dist/chunk-HTJ2FQW5.js +963 -0
  13. package/dist/chunk-HTJ2FQW5.js.map +1 -0
  14. package/dist/{chunk-R5B2XMN5.js → chunk-I4BDZDHX.js} +1614 -2141
  15. package/dist/chunk-I4BDZDHX.js.map +1 -0
  16. package/dist/{chunk-36DVUMQD.js → chunk-LPC64MD4.js} +2 -2
  17. package/dist/{chunk-72WV3ALS.js → chunk-OUUQSI3Y.js} +2 -2
  18. package/dist/{chunk-RMRYGICS.js → chunk-WP6TIVPH.js} +4 -4
  19. package/dist/core/index.d.ts +30 -1
  20. package/dist/hooks/index.d.ts +20 -1
  21. package/dist/hooks/index.js +1 -1
  22. package/dist/{index-BNKhgDdC.d.ts → index-2YySlz7X.d.ts} +3 -3
  23. package/dist/index.d.ts +11 -12
  24. package/dist/index.js +14 -95
  25. package/dist/index.native.d.ts +12 -30
  26. package/dist/index.native.js +17 -96
  27. package/dist/index.web.d.ts +132 -15
  28. package/dist/index.web.js +585 -46
  29. package/dist/index.web.js.map +1 -1
  30. package/dist/powersync-bridge/index.d.ts +1 -1
  31. package/dist/powersync-bridge/index.js +1 -1
  32. package/dist/query/index.js +10 -8
  33. package/dist/types/index.d.ts +1 -1
  34. package/dist/{useDbCount-Id14x_1P.d.ts → useDbCount-s-aR9YeV.d.ts} +1 -1
  35. package/dist/{useResolveFeedback-Ca2rh_Bs.d.ts → useResolveFeedback-DTGcHpCs.d.ts} +275 -390
  36. package/dist/with-auth/index.js +4 -4
  37. package/package.json +13 -12
  38. package/dist/chunk-2T6WTCP4.js.map +0 -1
  39. package/dist/chunk-R5B2XMN5.js.map +0 -1
  40. package/dist/chunk-X3HZLNBV.js.map +0 -1
  41. /package/dist/{chunk-36DVUMQD.js.map → chunk-LPC64MD4.js.map} +0 -0
  42. /package/dist/{chunk-72WV3ALS.js.map → chunk-OUUQSI3Y.js.map} +0 -0
  43. /package/dist/{chunk-RMRYGICS.js.map → chunk-WP6TIVPH.js.map} +0 -0
@@ -1,16 +1,15 @@
1
1
  import {
2
- normalizeFilter,
3
- useDbAdvanceFilterQuery
2
+ normalizeFilter
4
3
  } from "./chunk-H3LNH2NT.js";
5
4
  import {
6
5
  OperationLog
7
6
  } from "./chunk-7SCJNYTE.js";
8
7
  import {
9
8
  useDbQuery
10
- } from "./chunk-72WV3ALS.js";
9
+ } from "./chunk-OUUQSI3Y.js";
11
10
  import {
12
11
  useDbUpsert
13
- } from "./chunk-YERWPV6B.js";
12
+ } from "./chunk-3FHAKRDV.js";
14
13
  import {
15
14
  getSupabaseUrl
16
15
  } from "./chunk-GC3TBUWE.js";
@@ -33,7 +32,6 @@ import {
33
32
  normalizeResponse,
34
33
  useDeleteItem,
35
34
  useDeleteManyMutation,
36
- useInsertMutation,
37
35
  useQueriesForTableLoader,
38
36
  useQuery,
39
37
  useUpsertItem
@@ -47,1257 +45,145 @@ import {
47
45
  __toESM
48
46
  } from "./chunk-P4UZ7IXC.js";
49
47
 
50
- // src/useDbDelete.ts
48
+ // src/useMutationSuccess.ts
51
49
  import { c as _c } from "react/compiler-runtime";
52
- import { useMutation } from "@tanstack/react-query";
53
- function useDbDelete(relation, t0) {
54
- const $ = _c(14);
50
+ import { useEffect, useRef } from "react";
51
+ function useMutationSuccess(mutation, t0) {
52
+ const $ = _c(10);
55
53
  let t1;
56
54
  if ($[0] !== t0) {
57
- t1 = t0 === void 0 ? ["id"] : t0;
55
+ t1 = t0 === void 0 ? {} : t0;
58
56
  $[0] = t0;
59
57
  $[1] = t1;
60
58
  } else {
61
59
  t1 = $[1];
62
60
  }
63
- const primaryKeys = t1;
64
- const tableName = typeof relation === "object" ? relation.table : relation;
65
- const schemaName = typeof relation === "object" ? relation.schema : "public";
66
- const supabase = useSupabase();
67
- let t2;
68
- if ($[2] !== primaryKeys) {
69
- t2 = primaryKeys.map(_temp);
70
- $[2] = primaryKeys;
71
- $[3] = t2;
72
- } else {
73
- t2 = $[3];
74
- }
75
- const t3 = t2;
61
+ const options = t1;
62
+ const {
63
+ successMessage,
64
+ entityName,
65
+ enabled: t2,
66
+ onSuccess
67
+ } = options;
68
+ const enabled = t2 === void 0 ? true : t2;
69
+ const previousSuccessRef = useRef(false);
70
+ const previousDataRef = useRef(void 0);
71
+ let t3;
76
72
  let t4;
77
- if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
78
- t4 = {
79
- primaryKeys: t3,
80
- table: tableName,
81
- schema: schemaName
82
- };
83
- $[4] = schemaName;
84
- $[5] = t3;
85
- $[6] = tableName;
86
- $[7] = t4;
87
- } else {
88
- t4 = $[7];
89
- }
90
- const deleteItem = useDeleteItem(t4);
91
- let t5;
92
- if ($[8] !== deleteItem || $[9] !== primaryKeys || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
93
- t5 = {
94
- mutationFn: async (item) => {
95
- if (Array.isArray(item)) {
96
- throw new Error("Item cannot be an array.");
97
- }
98
- const deleteQuery = supabase.schema(schemaName).from(tableName).delete();
99
- primaryKeys.forEach((key) => {
100
- const keyStr = String(key);
101
- const value = item[keyStr];
102
- if (isUsable(value)) {
103
- deleteQuery.eq(keyStr, value);
73
+ if ($[2] !== enabled || $[3] !== entityName || $[4] !== mutation.data || $[5] !== mutation.isSuccess || $[6] !== onSuccess || $[7] !== successMessage) {
74
+ t3 = () => {
75
+ if (!enabled) {
76
+ return;
77
+ }
78
+ const isSuccess = mutation.isSuccess;
79
+ const hasNewData = mutation.data !== previousDataRef.current;
80
+ if (isSuccess && hasNewData && !previousSuccessRef.current) {
81
+ const message = successMessage || getDefaultSuccessMessage(entityName);
82
+ if (typeof window !== "undefined") {
83
+ try {
84
+ const {
85
+ toast
86
+ } = __require("@pol-studios/hooks");
87
+ toast.toast({
88
+ title: "Success",
89
+ description: message
90
+ });
91
+ } catch {
104
92
  }
105
- });
106
- const response = await deleteQuery.select().single();
107
- if (response.error) {
108
- throw response.error;
109
- }
110
- if (response.data) {
111
- deleteItem(response.data);
112
93
  } else {
113
- deleteItem(item);
94
+ try {
95
+ const {
96
+ Toast
97
+ } = __require("toastify-react-native");
98
+ Toast.success(message);
99
+ } catch {
100
+ }
114
101
  }
115
- return response.data;
102
+ onSuccess?.();
116
103
  }
104
+ previousSuccessRef.current = isSuccess;
105
+ previousDataRef.current = mutation.data;
117
106
  };
118
- $[8] = deleteItem;
119
- $[9] = primaryKeys;
120
- $[10] = schemaName;
121
- $[11] = supabase;
122
- $[12] = tableName;
123
- $[13] = t5;
107
+ t4 = [mutation.isSuccess, mutation.data, enabled, successMessage, entityName, onSuccess];
108
+ $[2] = enabled;
109
+ $[3] = entityName;
110
+ $[4] = mutation.data;
111
+ $[5] = mutation.isSuccess;
112
+ $[6] = onSuccess;
113
+ $[7] = successMessage;
114
+ $[8] = t3;
115
+ $[9] = t4;
124
116
  } else {
125
- t5 = $[13];
117
+ t3 = $[8];
118
+ t4 = $[9];
126
119
  }
127
- const deleteMutation = useMutation(t5);
128
- return deleteMutation;
129
- }
130
- function _temp(k) {
131
- return String(k);
120
+ useEffect(t3, t4);
121
+ return mutation;
132
122
  }
133
-
134
- // src/useDbInfiniteQuery.ts
135
- import { useInfiniteQuery } from "@tanstack/react-query";
136
- import { useMemo, useRef } from "react";
137
- function useDbInfiniteQuery(query, countPerLoad, config) {
138
- const initialQueryKey = encode(query, false).join("-");
139
- const lastKnownQuery = useRef(initialQueryKey);
140
- const currentPageNumber = useRef(1);
141
- if (lastKnownQuery.current != initialQueryKey) {
142
- lastKnownQuery.current = initialQueryKey;
143
- currentPageNumber.current = 1;
144
- }
145
- const isFetching = useRef(false);
146
- const queryKey = useMemo(() => encode(query, false), [initialQueryKey, config?.crossOrganization]);
147
- const getQuery = useInfiniteQuery({
148
- ...config,
149
- queryKey,
150
- queryFn: async ({
151
- pageParam,
152
- signal
153
- }) => {
154
- let adjustableQuery = query;
155
- const pageNumber = pageParam;
156
- if (config?.onQuery && config?.enableOnQuery) {
157
- config?.onQuery({
158
- query: adjustableQuery,
159
- pageParam: pageNumber
160
- });
161
- } else {
162
- adjustableQuery = adjustableQuery.range((pageNumber - 1) * countPerLoad, pageNumber * countPerLoad - 1);
163
- }
164
- adjustableQuery = adjustableQuery.abortSignal(signal);
165
- updatedCache.current = false;
166
- const response = await adjustableQuery;
167
- currentPageNumber.current = pageNumber;
168
- if (response.error) {
169
- throw response.error;
170
- } else {
171
- return response;
172
- }
173
- },
174
- initialPageParam: 1,
175
- getNextPageParam: (response_0, allResponses, lastParam) => {
176
- const pageParam_0 = lastParam;
177
- const resp = response_0;
178
- if (allResponses.length * countPerLoad >= (resp?.count ?? 0)) {
179
- return void 0;
180
- }
181
- return pageParam_0 + 1;
182
- }
183
- });
184
- const updatedCache = useRef(true);
185
- return useMemo(() => {
186
- const pages = getQuery.data?.pages;
187
- return {
188
- ...getQuery,
189
- count: pages?.[pages.length - 1]?.count,
190
- data: pages?.flatMap((x) => x.data ?? [])
191
- };
192
- }, [getQuery.data, currentPageNumber.current]);
123
+ function getDefaultSuccessMessage(entityName) {
124
+ if (!entityName) {
125
+ return "Saved successfully";
126
+ }
127
+ return `${entityName} saved successfully`;
193
128
  }
194
-
195
- // src/useDbInsert.ts
196
- import { c as _c2 } from "react/compiler-runtime";
197
- import { useMutation as useMutation2 } from "@tanstack/react-query";
198
- function useDbInsert(relation, t0, query, mutationOption) {
199
- const $ = _c2(11);
129
+ function useMutationSuccessRN(mutation, t0) {
130
+ const $ = _c(2);
200
131
  let t1;
201
132
  if ($[0] !== t0) {
202
- t1 = t0 === void 0 ? ["id"] : t0;
133
+ t1 = t0 === void 0 ? {} : t0;
203
134
  $[0] = t0;
204
135
  $[1] = t1;
205
136
  } else {
206
137
  t1 = $[1];
207
138
  }
208
- const primaryKeys = t1;
209
- const supabase = useSupabase();
210
- const tableName = typeof relation === "object" ? relation.table : relation;
211
- const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
212
- let t2;
213
- if ($[2] !== primaryKeys) {
214
- t2 = primaryKeys.map(_temp3);
215
- $[2] = primaryKeys;
216
- $[3] = t2;
217
- } else {
218
- t2 = $[3];
219
- }
220
- const primaryKeysAsStrings = t2;
221
- const t3 = supabase;
222
- let t4;
223
- if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
224
- t4 = t3.schema(schemaName).from(tableName);
225
- $[4] = schemaName;
226
- $[5] = t3;
227
- $[6] = tableName;
228
- $[7] = t4;
229
- } else {
230
- t4 = $[7];
231
- }
232
- const mutation = useInsertMutation(t4, primaryKeysAsStrings, query, mutationOption);
233
- let t5;
234
- if ($[8] !== mutation || $[9] !== primaryKeys) {
235
- t5 = {
236
- mutationFn: async (item) => {
237
- const primaryKeysNull = primaryKeys.filter((x) => x in item === false || isUsable(item[x]) === false).map(_temp2);
238
- const response = await mutation.mutateAsync([omit(item, primaryKeysNull)]);
239
- mutation.reset();
240
- return response?.[0];
241
- }
242
- };
243
- $[8] = mutation;
244
- $[9] = primaryKeys;
245
- $[10] = t5;
246
- } else {
247
- t5 = $[10];
248
- }
249
- const updateMutation = useMutation2(t5);
250
- return updateMutation;
251
- }
252
- function _temp2(k_0) {
253
- return String(k_0);
254
- }
255
- function _temp3(k) {
256
- return String(k);
139
+ const options = t1;
140
+ return useMutationSuccess(mutation, options);
257
141
  }
258
142
 
259
- // src/useDbMultiDelete.ts
260
- import { c as _c3 } from "react/compiler-runtime";
261
- import { useMutation as useMutation3 } from "@tanstack/react-query";
262
- function useDbMultiDelete(relation, t0) {
263
- const $ = _c3(10);
264
- let t1;
265
- if ($[0] !== t0) {
266
- t1 = t0 === void 0 ? ["id"] : t0;
267
- $[0] = t0;
268
- $[1] = t1;
269
- } else {
270
- t1 = $[1];
143
+ // src/adapters/types.ts
144
+ var ADAPTER_STRATEGIES = {
145
+ POWERSYNC: "powersync",
146
+ SUPABASE: "supabase",
147
+ CACHED: "cached",
148
+ HYBRID: "hybrid",
149
+ AUTO: "auto"
150
+ };
151
+
152
+ // src/adapters/auto-detector.ts
153
+ var BackendStatus = /* @__PURE__ */ ((BackendStatus2) => {
154
+ BackendStatus2["AVAILABLE"] = "available";
155
+ BackendStatus2["INITIALIZING"] = "initializing";
156
+ BackendStatus2["UNAVAILABLE"] = "unavailable";
157
+ return BackendStatus2;
158
+ })(BackendStatus || {});
159
+ var AdapterAutoDetector = class {
160
+ constructor(powerSyncDb, supabase, options = {}) {
161
+ this.powerSyncDb = powerSyncDb;
162
+ this.supabase = supabase;
163
+ this.options = {
164
+ preferPowerSync: options.preferPowerSync ?? true,
165
+ statusCheckTimeout: options.statusCheckTimeout ?? 1e3,
166
+ useOnlineUntilSynced: options.useOnlineUntilSynced ?? true
167
+ };
271
168
  }
272
- const primaryKeys = t1;
273
- const tableName = typeof relation === "object" ? relation.table : relation;
274
- const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
275
- const supabase = useSupabase();
276
- let t2;
277
- if ($[2] !== primaryKeys) {
278
- t2 = primaryKeys.map(_temp4);
279
- $[2] = primaryKeys;
280
- $[3] = t2;
281
- } else {
282
- t2 = $[3];
283
- }
284
- const primaryKeysAsStrings = t2;
285
- const t3 = supabase;
286
- let t4;
287
- if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
288
- t4 = t3.schema(schemaName).from(tableName);
289
- $[4] = schemaName;
290
- $[5] = t3;
291
- $[6] = tableName;
292
- $[7] = t4;
293
- } else {
294
- t4 = $[7];
295
- }
296
- const deleteManyMutation = useDeleteManyMutation(t4, primaryKeysAsStrings);
297
- let t5;
298
- if ($[8] !== deleteManyMutation) {
299
- t5 = {
300
- mutationFn: async (item) => {
301
- if (Array.isArray(item)) {
302
- const response = await deleteManyMutation.mutateAsync(item);
303
- return response;
304
- } else {
305
- throw new Error("Item must be an array.");
306
- }
307
- }
308
- };
309
- $[8] = deleteManyMutation;
310
- $[9] = t5;
311
- } else {
312
- t5 = $[9];
313
- }
314
- const deleteMutation = useMutation3(t5);
315
- return deleteMutation;
316
- }
317
- function _temp4(k) {
318
- return String(k);
319
- }
320
-
321
- // src/useDbMultiUpsert.ts
322
- import { c as _c4 } from "react/compiler-runtime";
323
- import { useMutation as useMutation4 } from "@tanstack/react-query";
324
- function useDbMultiUpsert(relation, t0, t1) {
325
- const $ = _c4(17);
326
- let t2;
327
- if ($[0] !== t0) {
328
- t2 = t0 === void 0 ? ["id"] : t0;
329
- $[0] = t0;
330
- $[1] = t2;
331
- } else {
332
- t2 = $[1];
333
- }
334
- const primaryKeys = t2;
335
- const query = t1 === void 0 ? "*" : t1;
336
- const supabase = useSupabase();
337
- const tableName = typeof relation === "object" ? relation.table : relation;
338
- const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
339
- const t3 = relation;
340
- let t4;
341
- if ($[2] !== primaryKeys || $[3] !== t3) {
342
- t4 = {
343
- primaryKeys,
344
- table: t3,
345
- schema: "public"
346
- };
347
- $[2] = primaryKeys;
348
- $[3] = t3;
349
- $[4] = t4;
350
- } else {
351
- t4 = $[4];
352
- }
353
- const upsertItem = useUpsertItem(t4);
354
- let t5;
355
- if ($[5] !== primaryKeys) {
356
- t5 = primaryKeys.map(_temp5);
357
- $[5] = primaryKeys;
358
- $[6] = t5;
359
- } else {
360
- t5 = $[6];
361
- }
362
- const primaryKeysAsStrings = t5;
363
- let t6;
364
- if ($[7] !== primaryKeys || $[8] !== primaryKeysAsStrings || $[9] !== query || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
365
- t6 = async function upsertItemAction2(item) {
366
- let task;
367
- if (Object.keys(item).length !== primaryKeys.length && primaryKeys.every((key_0) => key_0 in item && isUsable(item[key_0]))) {
368
- const updateObject = omit(item, primaryKeysAsStrings);
369
- task = supabase.schema(schemaName).from(tableName).update(updateObject);
370
- primaryKeys.forEach((key) => {
371
- task = task.eq(String(key), item[key]);
372
- });
373
- } else {
374
- task = supabase.schema(schemaName).from(tableName).insert(omit(item, primaryKeysAsStrings));
375
- }
376
- const response = await task.select(query);
377
- if (response.error) {
378
- throw response.error;
379
- }
380
- return response.data[0];
381
- };
382
- $[7] = primaryKeys;
383
- $[8] = primaryKeysAsStrings;
384
- $[9] = query;
385
- $[10] = schemaName;
386
- $[11] = supabase;
387
- $[12] = tableName;
388
- $[13] = t6;
389
- } else {
390
- t6 = $[13];
391
- }
392
- const upsertItemAction = t6;
393
- let t7;
394
- if ($[14] !== upsertItem || $[15] !== upsertItemAction) {
395
- t7 = {
396
- mutationFn: async (item_0) => {
397
- if (Array.isArray(item_0)) {
398
- const data = await Promise.all(item_0.map((x) => upsertItemAction(x)));
399
- data.filter(_temp22).forEach((x_1) => upsertItem(x_1));
400
- return data;
401
- }
402
- throw new Error("Item must be an array.");
403
- }
404
- };
405
- $[14] = upsertItem;
406
- $[15] = upsertItemAction;
407
- $[16] = t7;
408
- } else {
409
- t7 = $[16];
410
- }
411
- const updateMutation = useMutation4(t7);
412
- return updateMutation;
413
- }
414
- function _temp22(x_0) {
415
- return isUsable(x_0);
416
- }
417
- function _temp5(k) {
418
- return String(k);
419
- }
420
-
421
- // src/useDbPartialAdvanceQuery.ts
422
- import { c as _c5 } from "react/compiler-runtime";
423
- import { useLayoutEffect, useState } from "react";
424
- import { useSessionStorageState } from "@pol-studios/hooks/storage";
425
- function useDbPartialAdvanceQuery(query, itemCountPerPage, config) {
426
- const $ = _c5(54);
427
- const initialQuery = encode(query, false);
428
- const [id, setId] = useState(window.location.pathname);
429
- const [currentPage, setCurrentPage] = useSessionStorageState(`${id}-currentPage`, 1);
430
- const page = currentPage ?? 1;
431
- const t0 = query;
432
- let t1;
433
- if ($[0] !== itemCountPerPage || $[1] !== page || $[2] !== t0) {
434
- t1 = t0.range((page - 1) * itemCountPerPage, page * itemCountPerPage - 1);
435
- $[0] = itemCountPerPage;
436
- $[1] = page;
437
- $[2] = t0;
438
- $[3] = t1;
439
- } else {
440
- t1 = $[3];
441
- }
442
- const rangedQuery = t1;
443
- const t2 = config?.filterKey;
444
- const t3 = currentPage ?? 1;
445
- let t4;
446
- if ($[4] !== t3) {
447
- t4 = t3.toString();
448
- $[4] = t3;
449
- $[5] = t4;
450
- } else {
451
- t4 = $[5];
452
- }
453
- let t5;
454
- if ($[6] !== config || $[7] !== t2 || $[8] !== t4) {
455
- t5 = {
456
- ...config,
457
- filterKey: t2,
458
- count: "exact",
459
- key: t4
460
- };
461
- $[6] = config;
462
- $[7] = t2;
463
- $[8] = t4;
464
- $[9] = t5;
465
- } else {
466
- t5 = $[9];
467
- }
468
- const [baseQuery, filter, setFilters] = useDbAdvanceFilterQuery(rangedQuery, t5);
469
- let t6;
470
- if ($[10] !== filter) {
471
- t6 = JSON.stringify(omit(filter, ["pagination"]));
472
- $[10] = filter;
473
- $[11] = t6;
474
- } else {
475
- t6 = $[11];
476
- }
477
- const filterKey = t6;
478
- const select = initialQuery[4].split("&").find(_temp6);
479
- let t7;
480
- if ($[12] !== filterKey || $[13] !== id || $[14] !== initialQuery[3] || $[15] !== initialQuery[5] || $[16] !== initialQuery[6] || $[17] !== initialQuery[7] || $[18] !== initialQuery[8] || $[19] !== select || $[20] !== setId) {
481
- t7 = () => {
482
- const newId = [initialQuery[3], select, initialQuery[5], initialQuery[6], initialQuery[7], initialQuery[8], filterKey].join("-");
483
- console.log({
484
- newId,
485
- id
486
- });
487
- setId(newId);
488
- };
489
- $[12] = filterKey;
490
- $[13] = id;
491
- $[14] = initialQuery[3];
492
- $[15] = initialQuery[5];
493
- $[16] = initialQuery[6];
494
- $[17] = initialQuery[7];
495
- $[18] = initialQuery[8];
496
- $[19] = select;
497
- $[20] = setId;
498
- $[21] = t7;
499
- } else {
500
- t7 = $[21];
501
- }
502
- let t8;
503
- if ($[22] !== filterKey || $[23] !== initialQuery[3] || $[24] !== initialQuery[5] || $[25] !== initialQuery[6] || $[26] !== initialQuery[7] || $[27] !== initialQuery[8] || $[28] !== select) {
504
- t8 = [initialQuery[3], select, initialQuery[5], initialQuery[6], initialQuery[7], initialQuery[8], filterKey];
505
- $[22] = filterKey;
506
- $[23] = initialQuery[3];
507
- $[24] = initialQuery[5];
508
- $[25] = initialQuery[6];
509
- $[26] = initialQuery[7];
510
- $[27] = initialQuery[8];
511
- $[28] = select;
512
- $[29] = t8;
513
- } else {
514
- t8 = $[29];
515
- }
516
- useLayoutEffect(t7, t8);
517
- let t9;
518
- if ($[30] !== setCurrentPage) {
519
- t9 = () => {
520
- setCurrentPage(_temp23);
521
- };
522
- $[30] = setCurrentPage;
523
- $[31] = t9;
524
- } else {
525
- t9 = $[31];
526
- }
527
- const safeFetchNextPage = t9;
528
- let t10;
529
- if ($[32] !== setCurrentPage) {
530
- t10 = () => {
531
- setCurrentPage(_temp32);
532
- };
533
- $[32] = setCurrentPage;
534
- $[33] = t10;
535
- } else {
536
- t10 = $[33];
537
- }
538
- const fetchPreviousPage = t10;
539
- const pageCount = Math.max(Math.ceil((baseQuery.count ?? 0) / itemCountPerPage), 1);
540
- const t11 = currentPage ?? 1;
541
- let t12;
542
- if ($[34] !== baseQuery.count || $[35] !== baseQuery.data || $[36] !== currentPage || $[37] !== itemCountPerPage) {
543
- t12 = baseQuery.data ? toPagedResponse(baseQuery.data, currentPage ?? 1, baseQuery.count ?? baseQuery.data.length, itemCountPerPage) : null;
544
- $[34] = baseQuery.count;
545
- $[35] = baseQuery.data;
546
- $[36] = currentPage;
547
- $[37] = itemCountPerPage;
548
- $[38] = t12;
549
- } else {
550
- t12 = $[38];
551
- }
552
- const t13 = (currentPage ?? 1) < pageCount;
553
- const t14 = (currentPage ?? 1) > 1;
554
- const t15 = baseQuery.count ?? baseQuery.data?.length;
555
- let t16;
556
- if ($[39] !== baseQuery || $[40] !== fetchPreviousPage || $[41] !== pageCount || $[42] !== safeFetchNextPage || $[43] !== setCurrentPage || $[44] !== t11 || $[45] !== t12 || $[46] !== t13 || $[47] !== t14 || $[48] !== t15) {
557
- t16 = {
558
- ...baseQuery,
559
- clarification: baseQuery.clarification,
560
- fetchPreviousPage,
561
- fetchNextPage: safeFetchNextPage,
562
- currentPage: t11,
563
- setCurrentPage,
564
- data: t12,
565
- pageCount,
566
- hasNextPage: t13,
567
- hasPreviousPage: t14,
568
- count: t15
569
- };
570
- $[39] = baseQuery;
571
- $[40] = fetchPreviousPage;
572
- $[41] = pageCount;
573
- $[42] = safeFetchNextPage;
574
- $[43] = setCurrentPage;
575
- $[44] = t11;
576
- $[45] = t12;
577
- $[46] = t13;
578
- $[47] = t14;
579
- $[48] = t15;
580
- $[49] = t16;
581
- } else {
582
- t16 = $[49];
583
- }
584
- const request = t16;
585
- let t17;
586
- if ($[50] !== filter || $[51] !== request || $[52] !== setFilters) {
587
- t17 = [request, filter, setFilters];
588
- $[50] = filter;
589
- $[51] = request;
590
- $[52] = setFilters;
591
- $[53] = t17;
592
- } else {
593
- t17 = $[53];
594
- }
595
- return t17;
596
- }
597
- function _temp32(currentPage_1) {
598
- return (currentPage_1 ?? 1) - 1;
599
- }
600
- function _temp23(currentPage_0) {
601
- return (currentPage_0 ?? 1) + 1;
602
- }
603
- function _temp6(x) {
604
- return x.startsWith("select=");
605
- }
606
- function toPagedResponse(results, currentPage, totalCount, itemPerPage) {
607
- const newPage = {
608
- Items: results,
609
- CurrentPage: currentPage,
610
- ItemCount: totalCount,
611
- MaxCountPerPage: itemPerPage,
612
- PageCount: Math.max(Math.ceil(totalCount / itemPerPage), 1)
613
- };
614
- return newPage;
615
- }
616
-
617
- // src/useDbPartialQuery.ts
618
- import { c as _c6 } from "react/compiler-runtime";
619
- import { useSessionStorageState as useSessionStorageState2 } from "@pol-studios/hooks/storage";
620
- function useDbPartialQuery(query, itemCountPerPage, config) {
621
- const $ = _c6(28);
622
- let t0;
623
- if ($[0] !== query) {
624
- t0 = encode(query, false);
625
- $[0] = query;
626
- $[1] = t0;
627
- } else {
628
- t0 = $[1];
629
- }
630
- const initialQuery = t0;
631
- let t1;
632
- if ($[2] !== initialQuery[7] || $[3] !== initialQuery[8]) {
633
- t1 = [initialQuery[7], initialQuery[8]];
634
- $[2] = initialQuery[7];
635
- $[3] = initialQuery[8];
636
- $[4] = t1;
637
- } else {
638
- t1 = $[4];
639
- }
640
- const id = t1.join("-");
641
- const [currentPage, setCurrentPage] = useSessionStorageState2(id, 1);
642
- const page = currentPage ?? 1;
643
- const t2 = query;
644
- let t3;
645
- if ($[5] !== itemCountPerPage || $[6] !== page || $[7] !== t2) {
646
- t3 = t2.range((page - 1) * itemCountPerPage, page * itemCountPerPage - 1);
647
- $[5] = itemCountPerPage;
648
- $[6] = page;
649
- $[7] = t2;
650
- $[8] = t3;
651
- } else {
652
- t3 = $[8];
653
- }
654
- const rangedQuery = t3;
655
- const baseQuery = useDbQuery(rangedQuery, config);
656
- let t4;
657
- if ($[9] !== setCurrentPage) {
658
- t4 = () => {
659
- setCurrentPage(_temp7);
660
- };
661
- $[9] = setCurrentPage;
662
- $[10] = t4;
663
- } else {
664
- t4 = $[10];
665
- }
666
- const safeFetchNextPage = t4;
667
- let t5;
668
- if ($[11] !== setCurrentPage) {
669
- t5 = () => {
670
- setCurrentPage(_temp24);
671
- };
672
- $[11] = setCurrentPage;
673
- $[12] = t5;
674
- } else {
675
- t5 = $[12];
676
- }
677
- const fetchPreviousPage = t5;
678
- const pageCount = Math.max(Math.ceil((baseQuery.count ?? 0) / itemCountPerPage), 1);
679
- const t6 = currentPage ?? 1;
680
- let t7;
681
- if ($[13] !== baseQuery.count || $[14] !== baseQuery.data || $[15] !== currentPage || $[16] !== itemCountPerPage) {
682
- t7 = baseQuery.data ? toPagedResponse2(baseQuery.data, currentPage ?? 1, baseQuery.count ?? baseQuery.data.length, itemCountPerPage) : null;
683
- $[13] = baseQuery.count;
684
- $[14] = baseQuery.data;
685
- $[15] = currentPage;
686
- $[16] = itemCountPerPage;
687
- $[17] = t7;
688
- } else {
689
- t7 = $[17];
690
- }
691
- const t8 = (currentPage ?? 1) < pageCount;
692
- const t9 = (currentPage ?? 1) > 1;
693
- let t10;
694
- if ($[18] !== baseQuery || $[19] !== fetchPreviousPage || $[20] !== pageCount || $[21] !== safeFetchNextPage || $[22] !== setCurrentPage || $[23] !== t6 || $[24] !== t7 || $[25] !== t8 || $[26] !== t9) {
695
- t10 = {
696
- ...baseQuery,
697
- fetchPreviousPage,
698
- fetchNextPage: safeFetchNextPage,
699
- currentPage: t6,
700
- setCurrentPage,
701
- data: t7,
702
- pageCount,
703
- hasNextPage: t8,
704
- hasPreviousPage: t9
705
- };
706
- $[18] = baseQuery;
707
- $[19] = fetchPreviousPage;
708
- $[20] = pageCount;
709
- $[21] = safeFetchNextPage;
710
- $[22] = setCurrentPage;
711
- $[23] = t6;
712
- $[24] = t7;
713
- $[25] = t8;
714
- $[26] = t9;
715
- $[27] = t10;
716
- } else {
717
- t10 = $[27];
718
- }
719
- return t10;
720
- }
721
- function _temp24(currentPage_1) {
722
- return currentPage_1 - 1;
723
- }
724
- function _temp7(currentPage_0) {
725
- return currentPage_0 + 1;
726
- }
727
- function toPagedResponse2(results, currentPage, totalCount, itemPerPage) {
728
- const newPage = {
729
- Items: results,
730
- CurrentPage: currentPage,
731
- ItemCount: totalCount,
732
- MaxCountPerPage: itemPerPage,
733
- PageCount: Math.max(Math.ceil(totalCount / itemPerPage), 1)
734
- };
735
- return newPage;
736
- }
737
-
738
- // src/useDbRealtime.ts
739
- import { c as _c7 } from "react/compiler-runtime";
740
- import { useEffect, useState as useState2, useRef as useRef2 } from "react";
741
- import { REALTIME_POSTGRES_CHANGES_LISTEN_EVENT } from "@supabase/supabase-js";
742
- import { useDelayedValue } from "@pol-studios/hooks/state";
743
- function useDbRealtime(key, query, table, primaryKeys, options) {
744
- const $ = _c7(37);
745
- const supabase = useSupabase();
746
- const tableNameValue = typeof table === "string" ? table : table.table;
747
- const schemaValue = typeof table === "string" ? "public" : table.schema;
748
- const queriesForTable = useQueriesForTableLoader(tableNameValue);
749
- let t0;
750
- if ($[0] !== primaryKeys || $[1] !== schemaValue || $[2] !== tableNameValue) {
751
- t0 = {
752
- primaryKeys,
753
- table: tableNameValue,
754
- schema: schemaValue
755
- };
756
- $[0] = primaryKeys;
757
- $[1] = schemaValue;
758
- $[2] = tableNameValue;
759
- $[3] = t0;
760
- } else {
761
- t0 = $[3];
762
- }
763
- const deleteItem = useDeleteItem(t0);
764
- let t1;
765
- if ($[4] !== primaryKeys || $[5] !== schemaValue || $[6] !== tableNameValue) {
766
- t1 = {
767
- primaryKeys,
768
- table: tableNameValue,
769
- schema: schemaValue
770
- };
771
- $[4] = primaryKeys;
772
- $[5] = schemaValue;
773
- $[6] = tableNameValue;
774
- $[7] = t1;
775
- } else {
776
- t1 = $[7];
777
- }
778
- const upsertItem = useUpsertItem(t1);
779
- const [realtimeState, setRealtimeState] = useState2("CLOSED");
780
- const [retryTick, setRetryTick] = useState2(0);
781
- const channelRef = useRef2(null);
782
- const lastRetryTimeRef = useRef2(0);
783
- const retryCountRef = useRef2(0);
784
- const enabled = options?.enabled ?? true;
785
- const filter = options?.filter;
786
- const onChange = options?.onChange;
787
- const debouncedKey = useDelayedValue(key, 50);
788
- let t2;
789
- if ($[8] !== deleteItem || $[9] !== enabled || $[10] !== filter || $[11] !== onChange || $[12] !== primaryKeys || $[13] !== queriesForTable || $[14] !== query || $[15] !== retryTick || $[16] !== schemaValue || $[17] !== supabase || $[18] !== tableNameValue || $[19] !== upsertItem) {
790
- t2 = () => {
791
- if (!enabled) {
792
- if (channelRef.current) {
793
- channelRef.current.unsubscribe();
794
- supabase.removeChannel(channelRef.current);
795
- channelRef.current = null;
796
- }
797
- setRealtimeState("CLOSED");
798
- return;
799
- }
800
- const now = Date.now();
801
- const timeSinceLastRetry = now - lastRetryTimeRef.current;
802
- if (timeSinceLastRetry < 2e3 && retryTick > 0) {
803
- return;
804
- }
805
- if (channelRef.current) {
806
- channelRef.current.unsubscribe();
807
- supabase.removeChannel(channelRef.current);
808
- channelRef.current = null;
809
- }
810
- lastRetryTimeRef.current = now;
811
- retryCountRef.current = retryCountRef.current + 1;
812
- const channel = supabase.channel(newUuid()).on("postgres_changes", {
813
- event: "*",
814
- schema: schemaValue,
815
- table: tableNameValue,
816
- filter
817
- }, async (payload) => {
818
- let data = payload.new ?? payload.old;
819
- if (payload.new && Object.keys(payload.new).length > 0) {
820
- const selectQuery = buildNormalizedQuery({
821
- queriesForTable,
822
- query
823
- });
824
- if (payload.eventType !== REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE && selectQuery) {
825
- if (selectQuery.groupedUserQueryPaths?.every((x) => x.path in data) === false) {
826
- const qb = supabase.schema(payload.schema).from(payload.table).select(selectQuery.selectQuery);
827
- for (const pk of primaryKeys) {
828
- qb.eq(pk.toString(), data[pk]);
829
- }
830
- const res = await qb.single();
831
- if (res.data) {
832
- data = normalizeResponse(selectQuery.groupedPaths, res.data);
833
- }
834
- }
835
- }
836
- if ("changedBySessionId" in data) {
837
- const sessionId = data.changedBySessionId;
838
- if (sessionId !== UserSessionId) {
839
- await upsertItem(data);
840
- }
841
- } else {
842
- await upsertItem(data);
843
- }
844
- }
845
- if (payload.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
846
- await deleteItem(payload.old);
847
- }
848
- if (payload.errors?.length > 0) {
849
- setRealtimeState("CHANNEL_ERROR");
850
- }
851
- if (onChange) {
852
- onChange(payload);
853
- }
854
- }).on("postgres_changes", {
855
- event: "DELETE",
856
- schema: schemaValue,
857
- table: tableNameValue
858
- }, async (payload_0) => {
859
- if (payload_0.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
860
- await deleteItem(payload_0.old);
861
- }
862
- }).subscribe((status) => {
863
- setRealtimeState(status);
864
- if (status === "SUBSCRIBED") {
865
- retryCountRef.current = 0;
866
- }
867
- });
868
- channelRef.current = channel;
869
- return () => {
870
- if (channelRef.current) {
871
- channelRef.current.unsubscribe();
872
- supabase.removeChannel(channelRef.current);
873
- channelRef.current = null;
874
- }
875
- };
876
- };
877
- $[8] = deleteItem;
878
- $[9] = enabled;
879
- $[10] = filter;
880
- $[11] = onChange;
881
- $[12] = primaryKeys;
882
- $[13] = queriesForTable;
883
- $[14] = query;
884
- $[15] = retryTick;
885
- $[16] = schemaValue;
886
- $[17] = supabase;
887
- $[18] = tableNameValue;
888
- $[19] = upsertItem;
889
- $[20] = t2;
890
- } else {
891
- t2 = $[20];
892
- }
893
- let t3;
894
- if ($[21] !== primaryKeys) {
895
- t3 = primaryKeys.join(",");
896
- $[21] = primaryKeys;
897
- $[22] = t3;
898
- } else {
899
- t3 = $[22];
900
- }
901
- let t4;
902
- if ($[23] !== debouncedKey || $[24] !== enabled || $[25] !== filter || $[26] !== query || $[27] !== retryTick || $[28] !== schemaValue || $[29] !== supabase || $[30] !== t3 || $[31] !== tableNameValue) {
903
- t4 = [supabase, tableNameValue, schemaValue, enabled, filter, query, t3, retryTick, debouncedKey];
904
- $[23] = debouncedKey;
905
- $[24] = enabled;
906
- $[25] = filter;
907
- $[26] = query;
908
- $[27] = retryTick;
909
- $[28] = schemaValue;
910
- $[29] = supabase;
911
- $[30] = t3;
912
- $[31] = tableNameValue;
913
- $[32] = t4;
914
- } else {
915
- t4 = $[32];
916
- }
917
- useEffect(t2, t4);
918
- let t5;
919
- let t6;
920
- if ($[33] !== enabled || $[34] !== realtimeState) {
921
- t5 = () => {
922
- if (!enabled || realtimeState === "SUBSCRIBED") {
923
- retryCountRef.current = 0;
924
- return;
925
- }
926
- const delay = Math.min(5e3 * Math.pow(2, retryCountRef.current), 6e4);
927
- const id = setTimeout(() => {
928
- setRetryTick(_temp8);
929
- }, delay);
930
- return () => clearTimeout(id);
931
- };
932
- t6 = [realtimeState, enabled];
933
- $[33] = enabled;
934
- $[34] = realtimeState;
935
- $[35] = t5;
936
- $[36] = t6;
937
- } else {
938
- t5 = $[35];
939
- t6 = $[36];
940
- }
941
- useEffect(t5, t6);
942
- return realtimeState;
943
- }
944
- function _temp8(t) {
945
- return t + 1;
946
- }
947
-
948
- // src/useDbRealtimeQuery.tsx
949
- import { c as _c8 } from "react/compiler-runtime";
950
- function convertFilterToRealtimeQuery(filters) {
951
- function convert(filter) {
952
- if (!filter) return "";
953
- if ("path" in filter) {
954
- if (filter.path.includes(".")) return "";
955
- let valueString = filter.value?.toString() ?? "null";
956
- if (filter.operator === "in") {
957
- valueString = '("' + valueString.slice(2, valueString.length - 2).split(",").join('","') + '")';
958
- }
959
- return `${filter.path}=${filter.negate ? "not." : ""}${filter.operator}.${valueString}`;
960
- } else {
961
- if (filter.or) {
962
- return `(${filter.or.map((f) => convert(f)).join("|")})`;
963
- } else if (filter.and) {
964
- return `(${filter.and.map((f) => convert(f)).join("&")})`;
965
- }
966
- }
967
- return "";
968
- }
969
- return convert(filters[0]);
970
- }
971
- function useDbRealtimeQuery(query, config, t0) {
972
- const $ = _c8(27);
973
- let t1;
974
- if ($[0] !== t0) {
975
- t1 = t0 === void 0 ? ["id"] : t0;
976
- $[0] = t0;
977
- $[1] = t1;
978
- } else {
979
- t1 = $[1];
980
- }
981
- const primaryKeys = t1;
982
- const t2 = query;
983
- let t3;
984
- if ($[2] !== t2) {
985
- t3 = new PostgrestParser(t2);
986
- $[2] = t2;
987
- $[3] = t3;
988
- } else {
989
- t3 = $[3];
990
- }
991
- const parser = t3;
992
- const request = useQuery(query, config);
993
- let filter;
994
- let selectStatement;
995
- let t4;
996
- let t5;
997
- if ($[4] !== parser.filters || $[5] !== parser.select || $[6] !== query || $[7] !== request.data) {
998
- const queryKey = encode(query, false);
999
- let t62;
1000
- if ($[12] !== parser.filters || $[13] !== request.data) {
1001
- const filterString = convertFilterToRealtimeQuery(parser.filters);
1002
- filter = request.data && typeof request.data === "object" && "id" in request.data ? "id=eq." + request.data.id : filterString;
1003
- if (filter.includes('in.(\\"\\")')) {
1004
- filter = void 0;
1005
- }
1006
- t62 = isNullOrWhitespace(filter);
1007
- $[12] = parser.filters;
1008
- $[13] = request.data;
1009
- $[14] = filter;
1010
- $[15] = t62;
1011
- } else {
1012
- filter = $[14];
1013
- t62 = $[15];
1014
- }
1015
- if (t62) {
1016
- filter = void 0;
1017
- }
1018
- selectStatement = parser.select;
1019
- t4 = useDbRealtime;
1020
- t5 = queryKey.join("-");
1021
- $[4] = parser.filters;
1022
- $[5] = parser.select;
1023
- $[6] = query;
1024
- $[7] = request.data;
1025
- $[8] = filter;
1026
- $[9] = selectStatement;
1027
- $[10] = t4;
1028
- $[11] = t5;
1029
- } else {
1030
- filter = $[8];
1031
- selectStatement = $[9];
1032
- t4 = $[10];
1033
- t5 = $[11];
1034
- }
1035
- let t6;
1036
- if ($[16] !== parser.schema || $[17] !== parser.table) {
1037
- t6 = {
1038
- schema: parser.schema,
1039
- table: parser.table
1040
- };
1041
- $[16] = parser.schema;
1042
- $[17] = parser.table;
1043
- $[18] = t6;
1044
- } else {
1045
- t6 = $[18];
1046
- }
1047
- const t7 = typeof config?.enabled === "boolean" ? config.enabled : true;
1048
- let t8;
1049
- if ($[19] !== filter || $[20] !== t7) {
1050
- t8 = {
1051
- filter,
1052
- enabled: t7
1053
- };
1054
- $[19] = filter;
1055
- $[20] = t7;
1056
- $[21] = t8;
1057
- } else {
1058
- t8 = $[21];
1059
- }
1060
- const realtimeStatus = t4(t5, selectStatement, t6, primaryKeys, t8);
1061
- const outputRealtimeStatus = request.isFetching ? "Loading..." : realtimeStatus;
1062
- const t9 = request.data;
1063
- const t10 = realtimeStatus == "SUBSCRIBED";
1064
- let t11;
1065
- if ($[22] !== outputRealtimeStatus || $[23] !== request || $[24] !== t10 || $[25] !== t9) {
1066
- t11 = {
1067
- ...request,
1068
- data: t9,
1069
- realtimeStatus: outputRealtimeStatus,
1070
- isRealtimeConnected: t10,
1071
- isRealtimeLoading: request.isFetching
1072
- };
1073
- $[22] = outputRealtimeStatus;
1074
- $[23] = request;
1075
- $[24] = t10;
1076
- $[25] = t9;
1077
- $[26] = t11;
1078
- } else {
1079
- t11 = $[26];
1080
- }
1081
- return t11;
1082
- }
1083
-
1084
- // src/useDbUpdate.ts
1085
- import { c as _c9 } from "react/compiler-runtime";
1086
- import { useMutation as useMutation5 } from "@tanstack/react-query";
1087
- function useDbUpdate(relation, t0, query, mutationOption) {
1088
- const $ = _c9(14);
1089
- let t1;
1090
- if ($[0] !== t0) {
1091
- t1 = t0 === void 0 ? ["id"] : t0;
1092
- $[0] = t0;
1093
- $[1] = t1;
1094
- } else {
1095
- t1 = $[1];
1096
- }
1097
- const primaryKeys = t1;
1098
- const supabase = useSupabase();
1099
- const tableName = typeof relation === "object" ? relation.table : relation;
1100
- const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
1101
- let t2;
1102
- if ($[2] !== primaryKeys) {
1103
- t2 = primaryKeys.map(_temp9);
1104
- $[2] = primaryKeys;
1105
- $[3] = t2;
1106
- } else {
1107
- t2 = $[3];
1108
- }
1109
- const primaryKeysAsStrings = t2;
1110
- const t3 = primaryKeysAsStrings;
1111
- const t4 = relation;
1112
- let t5;
1113
- if ($[4] !== t3 || $[5] !== t4) {
1114
- t5 = {
1115
- primaryKeys: t3,
1116
- table: t4,
1117
- schema: "public"
1118
- };
1119
- $[4] = t3;
1120
- $[5] = t4;
1121
- $[6] = t5;
1122
- } else {
1123
- t5 = $[6];
1124
- }
1125
- const upsertItem = useUpsertItem(t5);
1126
- let t6;
1127
- if ($[7] !== primaryKeys || $[8] !== primaryKeysAsStrings || $[9] !== schemaName || $[10] !== supabase || $[11] !== tableName || $[12] !== upsertItem) {
1128
- t6 = {
1129
- mutationFn: async (item) => {
1130
- let response = null;
1131
- if (primaryKeys.every((x_0) => x_0 in item && isUsable(item[x_0]))) {
1132
- const query_0 = supabase.schema(schemaName).from(tableName).update(omit(item, primaryKeysAsStrings));
1133
- primaryKeys.forEach((x) => {
1134
- query_0.eq(String(x), item[x]);
1135
- });
1136
- const queryResponse = await query_0.select().single().throwOnError();
1137
- if (queryResponse.data) {
1138
- response = queryResponse.data;
1139
- upsertItem(response);
1140
- }
1141
- }
1142
- return response;
1143
- }
1144
- };
1145
- $[7] = primaryKeys;
1146
- $[8] = primaryKeysAsStrings;
1147
- $[9] = schemaName;
1148
- $[10] = supabase;
1149
- $[11] = tableName;
1150
- $[12] = upsertItem;
1151
- $[13] = t6;
1152
- } else {
1153
- t6 = $[13];
1154
- }
1155
- const updateMutation = useMutation5(t6);
1156
- return updateMutation;
1157
- }
1158
- function _temp9(k) {
1159
- return String(k);
1160
- }
1161
-
1162
- // src/useMutationSuccess.ts
1163
- import { c as _c10 } from "react/compiler-runtime";
1164
- import { useEffect as useEffect2, useRef as useRef3 } from "react";
1165
- function useMutationSuccess(mutation, t0) {
1166
- const $ = _c10(10);
1167
- let t1;
1168
- if ($[0] !== t0) {
1169
- t1 = t0 === void 0 ? {} : t0;
1170
- $[0] = t0;
1171
- $[1] = t1;
1172
- } else {
1173
- t1 = $[1];
1174
- }
1175
- const options = t1;
1176
- const {
1177
- successMessage,
1178
- entityName,
1179
- enabled: t2,
1180
- onSuccess
1181
- } = options;
1182
- const enabled = t2 === void 0 ? true : t2;
1183
- const previousSuccessRef = useRef3(false);
1184
- const previousDataRef = useRef3(void 0);
1185
- let t3;
1186
- let t4;
1187
- if ($[2] !== enabled || $[3] !== entityName || $[4] !== mutation.data || $[5] !== mutation.isSuccess || $[6] !== onSuccess || $[7] !== successMessage) {
1188
- t3 = () => {
1189
- if (!enabled) {
1190
- return;
1191
- }
1192
- const isSuccess = mutation.isSuccess;
1193
- const hasNewData = mutation.data !== previousDataRef.current;
1194
- if (isSuccess && hasNewData && !previousSuccessRef.current) {
1195
- const message = successMessage || getDefaultSuccessMessage(entityName);
1196
- if (typeof window !== "undefined") {
1197
- try {
1198
- const {
1199
- toast
1200
- } = __require("@pol-studios/hooks");
1201
- toast.toast({
1202
- title: "Success",
1203
- description: message
1204
- });
1205
- } catch {
1206
- }
1207
- } else {
1208
- try {
1209
- const {
1210
- Toast
1211
- } = __require("toastify-react-native");
1212
- Toast.success(message);
1213
- } catch {
1214
- }
1215
- }
1216
- onSuccess?.();
1217
- }
1218
- previousSuccessRef.current = isSuccess;
1219
- previousDataRef.current = mutation.data;
1220
- };
1221
- t4 = [mutation.isSuccess, mutation.data, enabled, successMessage, entityName, onSuccess];
1222
- $[2] = enabled;
1223
- $[3] = entityName;
1224
- $[4] = mutation.data;
1225
- $[5] = mutation.isSuccess;
1226
- $[6] = onSuccess;
1227
- $[7] = successMessage;
1228
- $[8] = t3;
1229
- $[9] = t4;
1230
- } else {
1231
- t3 = $[8];
1232
- t4 = $[9];
1233
- }
1234
- useEffect2(t3, t4);
1235
- return mutation;
1236
- }
1237
- function getDefaultSuccessMessage(entityName) {
1238
- if (!entityName) {
1239
- return "Saved successfully";
1240
- }
1241
- return `${entityName} saved successfully`;
1242
- }
1243
- function useMutationSuccessRN(mutation, t0) {
1244
- const $ = _c10(2);
1245
- let t1;
1246
- if ($[0] !== t0) {
1247
- t1 = t0 === void 0 ? {} : t0;
1248
- $[0] = t0;
1249
- $[1] = t1;
1250
- } else {
1251
- t1 = $[1];
1252
- }
1253
- const options = t1;
1254
- return useMutationSuccess(mutation, options);
1255
- }
1256
-
1257
- // src/adapters/types.ts
1258
- var ADAPTER_STRATEGIES = {
1259
- POWERSYNC: "powersync",
1260
- SUPABASE: "supabase",
1261
- CACHED: "cached",
1262
- HYBRID: "hybrid",
1263
- AUTO: "auto"
1264
- };
1265
-
1266
- // src/adapters/auto-detector.ts
1267
- var BackendStatus = /* @__PURE__ */ ((BackendStatus2) => {
1268
- BackendStatus2["AVAILABLE"] = "available";
1269
- BackendStatus2["INITIALIZING"] = "initializing";
1270
- BackendStatus2["UNAVAILABLE"] = "unavailable";
1271
- return BackendStatus2;
1272
- })(BackendStatus || {});
1273
- var AdapterAutoDetector = class {
1274
- constructor(powerSyncDb, supabase, options = {}) {
1275
- this.powerSyncDb = powerSyncDb;
1276
- this.supabase = supabase;
1277
- this.options = {
1278
- preferPowerSync: options.preferPowerSync ?? true,
1279
- statusCheckTimeout: options.statusCheckTimeout ?? 1e3,
1280
- useOnlineUntilSynced: options.useOnlineUntilSynced ?? true
1281
- };
1282
- }
1283
- options;
1284
- listeners = /* @__PURE__ */ new Set();
1285
- lastResult = null;
1286
- syncStatus = null;
1287
- /**
1288
- * Update the sync status from PowerSync.
1289
- * Called when sync status changes to re-evaluate backend recommendation.
1290
- *
1291
- * @param status - Current sync status or null if not available
1292
- */
1293
- updateSyncStatus(status) {
1294
- const hadSynced = this.syncStatus?.hasSynced;
1295
- const hasSyncedNow = status?.hasSynced;
1296
- const changed = hadSynced !== hasSyncedNow;
1297
- this.syncStatus = status;
1298
- if (changed) {
1299
- this.detect();
1300
- }
169
+ options;
170
+ listeners = /* @__PURE__ */ new Set();
171
+ lastResult = null;
172
+ syncStatus = null;
173
+ /**
174
+ * Update the sync status from PowerSync.
175
+ * Called when sync status changes to re-evaluate backend recommendation.
176
+ *
177
+ * @param status - Current sync status or null if not available
178
+ */
179
+ updateSyncStatus(status) {
180
+ const hadSynced = this.syncStatus?.hasSynced;
181
+ const hasSyncedNow = status?.hasSynced;
182
+ const changed = hadSynced !== hasSyncedNow;
183
+ this.syncStatus = status;
184
+ if (changed) {
185
+ this.detect();
186
+ }
1301
187
  }
1302
188
  /**
1303
189
  * Get current sync status.
@@ -2293,9 +1179,9 @@ async function getErrorBody(response) {
2293
1179
  }
2294
1180
 
2295
1181
  // src/useAI.ts
2296
- import { c as _c11 } from "react/compiler-runtime";
1182
+ import { c as _c2 } from "react/compiler-runtime";
2297
1183
  function useAI() {
2298
- const $ = _c11(2);
1184
+ const $ = _c2(2);
2299
1185
  const supabase = useSupabase();
2300
1186
  let t0;
2301
1187
  if ($[0] !== supabase) {
@@ -2333,7 +1219,7 @@ function useAI() {
2333
1219
  }
2334
1220
 
2335
1221
  // src/useServerAvailability.ts
2336
- import { useState as useState3, useEffect as useEffect3, useCallback } from "react";
1222
+ import { useState, useEffect as useEffect2, useCallback } from "react";
2337
1223
  var CHECK_TIMEOUT = 1e4;
2338
1224
  var CHECK_INTERVAL = 3e4;
2339
1225
  function useServerAvailability(options) {
@@ -2342,10 +1228,10 @@ function useServerAvailability(options) {
2342
1228
  checkInterval = CHECK_INTERVAL,
2343
1229
  timeout = CHECK_TIMEOUT
2344
1230
  } = options || {};
2345
- const [isAvailable, setIsAvailable] = useState3(null);
2346
- const [isChecking, setIsChecking] = useState3(false);
2347
- const [lastChecked, setLastChecked] = useState3(null);
2348
- const [error, setError] = useState3(null);
1231
+ const [isAvailable, setIsAvailable] = useState(null);
1232
+ const [isChecking, setIsChecking] = useState(false);
1233
+ const [lastChecked, setLastChecked] = useState(null);
1234
+ const [error, setError] = useState(null);
2349
1235
  const checkAvailability = useCallback(async () => {
2350
1236
  if (!enabled) return;
2351
1237
  setIsChecking(true);
@@ -2390,12 +1276,12 @@ function useServerAvailability(options) {
2390
1276
  setIsChecking(false);
2391
1277
  }
2392
1278
  }, [enabled, timeout]);
2393
- useEffect3(() => {
1279
+ useEffect2(() => {
2394
1280
  if (enabled) {
2395
1281
  checkAvailability();
2396
1282
  }
2397
1283
  }, [enabled, checkAvailability]);
2398
- useEffect3(() => {
1284
+ useEffect2(() => {
2399
1285
  if (!enabled || isAvailable !== false) return;
2400
1286
  const intervalId = setInterval(() => {
2401
1287
  checkAvailability();
@@ -2412,7 +1298,7 @@ function useServerAvailability(options) {
2412
1298
  }
2413
1299
 
2414
1300
  // src/useSearchQuery.ts
2415
- import { useMemo as useMemo3 } from "react";
1301
+ import { useMemo } from "react";
2416
1302
  import React from "react";
2417
1303
  function useSearchQuery(baseQuery, searchText, columns, options = {
2418
1304
  isOptional: true,
@@ -2437,996 +1323,1588 @@ function useSearchQuery(baseQuery, searchText, columns, options = {
2437
1323
  signal
2438
1324
  }
2439
1325
  };
2440
- }
2441
- return useMemo3(() => {
2442
- const qb = baseQuery;
2443
- const {
2444
- url: url_0,
2445
- method: method_0,
2446
- body: body_0,
2447
- signal: signal_0
2448
- } = original.current.original;
2449
- qb.url = new URL(url_0.toString());
2450
- qb.method = method_0;
2451
- if (method_0 !== "GET" && method_0 !== "HEAD") {
2452
- qb.body = body_0;
2453
- } else {
2454
- delete qb.body;
1326
+ }
1327
+ return useMemo(() => {
1328
+ const qb = baseQuery;
1329
+ const {
1330
+ url: url_0,
1331
+ method: method_0,
1332
+ body: body_0,
1333
+ signal: signal_0
1334
+ } = original.current.original;
1335
+ qb.url = new URL(url_0.toString());
1336
+ qb.method = method_0;
1337
+ if (method_0 !== "GET" && method_0 !== "HEAD") {
1338
+ qb.body = body_0;
1339
+ } else {
1340
+ delete qb.body;
1341
+ }
1342
+ qb.signal = signal_0;
1343
+ const term = searchText.trim();
1344
+ if (term) {
1345
+ const clauses = columns.map((col) => {
1346
+ const [tbl, colName] = col.split(".");
1347
+ return `${colName ?? tbl}.ilike.%${escapeLikePattern(term)}%`;
1348
+ });
1349
+ clauses.push(...options.additionCondition.filter(Boolean));
1350
+ qb.or(clauses.join(","), {
1351
+ referencedTable: columns.find((c) => c.includes("."))?.split(".")[0]
1352
+ });
1353
+ } else if (!options.isOptional) {
1354
+ const conds = options.additionCondition.filter(Boolean);
1355
+ conds?.length ? qb.or(conds.join(",")) : qb.limit(0);
1356
+ }
1357
+ return qb;
1358
+ }, [baseQuery, searchText, columns.join(","), options.isOptional, options.additionCondition.join(",")]);
1359
+ }
1360
+ function escapeLikePattern(text) {
1361
+ return text?.replace(/[%_]/g, "\\$&");
1362
+ }
1363
+
1364
+ // src/useLiveChangeTracking.ts
1365
+ import { c as _c3 } from "react/compiler-runtime";
1366
+ import { useEffect as useEffect3, useState as useState2 } from "react";
1367
+ var import_moment = __toESM(require_moment(), 1);
1368
+ function useLiveChangeTracking(tableName, item, action) {
1369
+ const $ = _c3(12);
1370
+ const [changeLog, setChangeLog] = useState2(null);
1371
+ const [oldItem, setOldItem] = useState2(null);
1372
+ const supabase = useSupabase();
1373
+ let t0;
1374
+ if ($[0] !== item || $[1] !== oldItem || $[2] !== supabase || $[3] !== tableName) {
1375
+ t0 = () => {
1376
+ setChangeLog(null);
1377
+ if (isUsable(item) === false) {
1378
+ return;
1379
+ }
1380
+ if (isUsable(oldItem) === false) {
1381
+ setOldItem(item);
1382
+ return;
1383
+ }
1384
+ const itemId = item.id;
1385
+ if (isUsable(itemId) === false) {
1386
+ return;
1387
+ }
1388
+ const changes = getObjectChanges(oldItem, item);
1389
+ if (Object.keys(changes).length === 0) {
1390
+ return;
1391
+ }
1392
+ supabase.schema("core").from("OperationLog").select().filter("tableName", "eq", tableName).filter("recordId", "eq", itemId).order("changeAt", {
1393
+ ascending: false
1394
+ }).limit(1).single().then((x) => {
1395
+ if (isUsable(x.data) === false) {
1396
+ return;
1397
+ }
1398
+ const data = x.data;
1399
+ if (data.sessionId === UserSessionId) {
1400
+ return;
1401
+ }
1402
+ const changeLog_0 = {
1403
+ modifiedByUserId: data.changeBy,
1404
+ changedOn: import_moment.default.utc(data.changeAt),
1405
+ changes
1406
+ };
1407
+ setChangeLog(changeLog_0);
1408
+ });
1409
+ setOldItem(item);
1410
+ };
1411
+ $[0] = item;
1412
+ $[1] = oldItem;
1413
+ $[2] = supabase;
1414
+ $[3] = tableName;
1415
+ $[4] = t0;
1416
+ } else {
1417
+ t0 = $[4];
1418
+ }
1419
+ let t1;
1420
+ if ($[5] !== item) {
1421
+ t1 = [item];
1422
+ $[5] = item;
1423
+ $[6] = t1;
1424
+ } else {
1425
+ t1 = $[6];
1426
+ }
1427
+ useEffect3(t0, t1);
1428
+ let t2;
1429
+ if ($[7] !== action || $[8] !== changeLog) {
1430
+ t2 = () => {
1431
+ if (isUsable(changeLog) && action) {
1432
+ action(changeLog.changes, changeLog);
1433
+ }
1434
+ };
1435
+ $[7] = action;
1436
+ $[8] = changeLog;
1437
+ $[9] = t2;
1438
+ } else {
1439
+ t2 = $[9];
1440
+ }
1441
+ let t3;
1442
+ if ($[10] !== changeLog) {
1443
+ t3 = [changeLog];
1444
+ $[10] = changeLog;
1445
+ $[11] = t3;
1446
+ } else {
1447
+ t3 = $[11];
1448
+ }
1449
+ useEffect3(t2, t3);
1450
+ return changeLog;
1451
+ }
1452
+
1453
+ // src/useLatestOperationLog.ts
1454
+ import { c as _c4 } from "react/compiler-runtime";
1455
+ function useLatestOperationLog(tableName, recordId) {
1456
+ const $ = _c4(8);
1457
+ const supabase = useSupabase();
1458
+ const t0 = supabase;
1459
+ let t1;
1460
+ if ($[0] !== recordId || $[1] !== t0 || $[2] !== tableName) {
1461
+ t1 = t0.schema("core").from("OperationLog").select(OperationLog.defaultQuery).eq("recordId", String(recordId)).eq("tableName", tableName).order("changeAt", {
1462
+ ascending: false
1463
+ }).limit(1).maybeSingle();
1464
+ $[0] = recordId;
1465
+ $[1] = t0;
1466
+ $[2] = tableName;
1467
+ $[3] = t1;
1468
+ } else {
1469
+ t1 = $[3];
1470
+ }
1471
+ let t2;
1472
+ if ($[4] !== recordId) {
1473
+ t2 = isUsable(recordId);
1474
+ $[4] = recordId;
1475
+ $[5] = t2;
1476
+ } else {
1477
+ t2 = $[5];
1478
+ }
1479
+ let t3;
1480
+ if ($[6] !== t2) {
1481
+ t3 = {
1482
+ refetchOnMount: true,
1483
+ refetchOnWindowFocus: true,
1484
+ staleTime: 0,
1485
+ enabled: t2
1486
+ };
1487
+ $[6] = t2;
1488
+ $[7] = t3;
1489
+ } else {
1490
+ t3 = $[7];
1491
+ }
1492
+ return useDbQuery(t1, t3);
1493
+ }
1494
+
1495
+ // src/useAutosaveState.ts
1496
+ import { useCallback as useCallback2, useEffect as useEffect4, useMemo as useMemo2, useRef as useRef3, useState as useState3 } from "react";
1497
+ function newTimeActivity(date) {
1498
+ return {
1499
+ activityDate: date.clone().startOf("day").toISOString(true),
1500
+ description: "",
1501
+ hasRequestBillableChange: false,
1502
+ hasRequestVerification: false,
1503
+ hours: 0,
1504
+ userNotes: "",
1505
+ adminNotes: "",
1506
+ userId: null,
1507
+ clientId: null,
1508
+ projectId: null,
1509
+ workingPhaseId: null,
1510
+ roleId: null,
1511
+ taskId: null,
1512
+ subtaskId: null,
1513
+ weeklyTimesheetId: null,
1514
+ id: null,
1515
+ BillingDetails: {
1516
+ status: "Unknown",
1517
+ id: null,
1518
+ orderHint: "",
1519
+ chargeTableId: null,
1520
+ cosmosId: null,
1521
+ amount: 0,
1522
+ rate: 0,
1523
+ type: "TimeActivity"
1524
+ }
1525
+ };
1526
+ }
1527
+ function getNewValue(action, prevState) {
1528
+ return typeof action === "function" ? action(prevState) : action;
1529
+ }
1530
+ function useAutosaveState(relation, defaultValue, options) {
1531
+ const [value, setValue] = useState3(() => defaultValue);
1532
+ const [baseValue, setBaseValue] = useState3(() => defaultValue);
1533
+ const baseValueRef = useRef3(defaultValue);
1534
+ const pendingChangesRef = useRef3(/* @__PURE__ */ new Map());
1535
+ const currentId = useRef3(null);
1536
+ const newOptions = useMemo2(() => options ? {
1537
+ ...options,
1538
+ primaryKeys: options.primaryKeys ?? ["id"]
1539
+ } : {
1540
+ delay: 200,
1541
+ primaryKeys: ["id"]
1542
+ }, [options]);
1543
+ const upsertMutation = useDbUpsert(relation, {
1544
+ invalidateTables: [relation]
1545
+ });
1546
+ const saveEntityChanges = useCallback2(async (entityId) => {
1547
+ if (__DEV__) {
1548
+ console.log("[Autosave] saveEntityChanges called:", {
1549
+ entityId,
1550
+ relation,
1551
+ hasPendingEntry: pendingChangesRef.current.has(entityId)
1552
+ });
1553
+ }
1554
+ const pending = pendingChangesRef.current.get(entityId);
1555
+ if (!pending) {
1556
+ if (__DEV__) {
1557
+ console.log("[Autosave] No pending changes found for entity:", entityId);
1558
+ }
1559
+ return;
1560
+ }
1561
+ const changes = diff(pending.baseValue, pending.currentValue);
1562
+ if (__DEV__) {
1563
+ console.log("[Autosave] Computed diff:", {
1564
+ entityId,
1565
+ relation,
1566
+ changeKeys: Object.keys(changes),
1567
+ changes,
1568
+ baseValue: pending.baseValue,
1569
+ currentValue: pending.currentValue
1570
+ });
1571
+ }
1572
+ if (Object.keys(changes).length === 0) {
1573
+ if (__DEV__) {
1574
+ console.log("[Autosave] No changes detected, skipping save for:", entityId);
1575
+ }
1576
+ pendingChangesRef.current.delete(entityId);
1577
+ return;
1578
+ }
1579
+ const patch = {
1580
+ ...changes,
1581
+ id: entityId
1582
+ };
1583
+ const finalPatch = newOptions.transformBeforeMutation ? newOptions.transformBeforeMutation(patch) : patch;
1584
+ if (__DEV__) {
1585
+ console.log("[Autosave] Calling mutateAsync:", {
1586
+ entityId,
1587
+ relation,
1588
+ patch,
1589
+ finalPatch,
1590
+ hasTransform: !!newOptions.transformBeforeMutation
1591
+ });
2455
1592
  }
2456
- qb.signal = signal_0;
2457
- const term = searchText.trim();
2458
- if (term) {
2459
- const clauses = columns.map((col) => {
2460
- const [tbl, colName] = col.split(".");
2461
- return `${colName ?? tbl}.ilike.%${escapeLikePattern(term)}%`;
1593
+ try {
1594
+ const result = await upsertMutation.mutateAsync(finalPatch);
1595
+ if (__DEV__) {
1596
+ console.log("[Autosave] mutateAsync SUCCESS:", {
1597
+ entityId,
1598
+ relation,
1599
+ finalPatch,
1600
+ result
1601
+ });
1602
+ }
1603
+ pendingChangesRef.current.delete(entityId);
1604
+ } catch (error) {
1605
+ if (__DEV__) {
1606
+ console.error("[Autosave] mutateAsync FAILED:", {
1607
+ entityId,
1608
+ relation,
1609
+ finalPatch,
1610
+ error,
1611
+ errorMessage: error instanceof Error ? error.message : String(error),
1612
+ errorStack: error instanceof Error ? error.stack : void 0
1613
+ });
1614
+ }
1615
+ throw error;
1616
+ }
1617
+ }, [relation, upsertMutation, newOptions.transformBeforeMutation]);
1618
+ const updateValue = useCallback2((update) => {
1619
+ setValue((prev) => {
1620
+ const newValue = getNewValue(update, prev);
1621
+ const entityId_0 = newValue.id;
1622
+ if (!entityId_0) return newValue;
1623
+ let pending_0 = pendingChangesRef.current.get(entityId_0);
1624
+ if (!pending_0) {
1625
+ pending_0 = {
1626
+ baseValue: baseValueRef.current,
1627
+ currentValue: newValue,
1628
+ timeoutId: null
1629
+ };
1630
+ pendingChangesRef.current.set(entityId_0, pending_0);
1631
+ if (__DEV__) {
1632
+ console.log("[Autosave] Created new pending entry using baseValueRef:", {
1633
+ entityId: entityId_0,
1634
+ baseValueId: baseValueRef.current?.id
1635
+ });
1636
+ }
1637
+ } else {
1638
+ pending_0.currentValue = newValue;
1639
+ }
1640
+ if (pending_0.timeoutId) {
1641
+ clearTimeout(pending_0.timeoutId);
1642
+ }
1643
+ pending_0.timeoutId = setTimeout(() => {
1644
+ saveEntityChanges(entityId_0);
1645
+ }, newOptions.delay);
1646
+ return newValue;
1647
+ });
1648
+ }, [saveEntityChanges, newOptions.delay]);
1649
+ const setNewEntity = useCallback2((newEntity) => {
1650
+ baseValueRef.current = newEntity;
1651
+ if (__DEV__) {
1652
+ console.log("[Autosave] setNewEntity - baseValueRef updated synchronously:", {
1653
+ entityId: newEntity.id,
1654
+ relation
2462
1655
  });
2463
- clauses.push(...options.additionCondition.filter(Boolean));
2464
- qb.or(clauses.join(","), {
2465
- referencedTable: columns.find((c) => c.includes("."))?.split(".")[0]
1656
+ }
1657
+ setValue(newEntity);
1658
+ setBaseValue(newEntity);
1659
+ currentId.current = newEntity.id;
1660
+ }, [relation]);
1661
+ useEffect4(() => {
1662
+ return () => {
1663
+ pendingChangesRef.current.forEach((pending_1) => {
1664
+ if (pending_1.timeoutId) clearTimeout(pending_1.timeoutId);
2466
1665
  });
2467
- } else if (!options.isOptional) {
2468
- const conds = options.additionCondition.filter(Boolean);
2469
- conds?.length ? qb.or(conds.join(",")) : qb.limit(0);
1666
+ };
1667
+ }, []);
1668
+ const saveCurrentValue = useCallback2(async () => {
1669
+ if (currentId.current) {
1670
+ await saveEntityChanges(currentId.current);
2470
1671
  }
2471
- return qb;
2472
- }, [baseQuery, searchText, columns.join(","), options.isOptional, options.additionCondition.join(",")]);
2473
- }
2474
- function escapeLikePattern(text) {
2475
- return text?.replace(/[%_]/g, "\\$&");
1672
+ }, [saveEntityChanges]);
1673
+ return [value, updateValue, upsertMutation, setValue, setNewEntity, saveCurrentValue];
2476
1674
  }
2477
1675
 
2478
- // src/useLiveChangeTracking.ts
2479
- import { c as _c12 } from "react/compiler-runtime";
2480
- import { useEffect as useEffect4, useState as useState4 } from "react";
2481
- var import_moment = __toESM(require_moment(), 1);
2482
- function useLiveChangeTracking(tableName, item, action) {
2483
- const $ = _c12(12);
2484
- const [changeLog, setChangeLog] = useState4(null);
2485
- const [oldItem, setOldItem] = useState4(null);
2486
- const supabase = useSupabase();
1676
+ // src/useToastError.ts
1677
+ import { c as _c5 } from "react/compiler-runtime";
1678
+ import { useEffect as useEffect5 } from "react";
1679
+ import { useToast } from "@pol-studios/hooks/toast";
1680
+ function useToastError(mutation) {
1681
+ const $ = _c5(5);
1682
+ const toast = useToast();
2487
1683
  let t0;
2488
- if ($[0] !== item || $[1] !== oldItem || $[2] !== supabase || $[3] !== tableName) {
1684
+ if ($[0] !== mutation.error || $[1] !== toast) {
2489
1685
  t0 = () => {
2490
- setChangeLog(null);
2491
- if (isUsable(item) === false) {
2492
- return;
2493
- }
2494
- if (isUsable(oldItem) === false) {
2495
- setOldItem(item);
2496
- return;
2497
- }
2498
- const itemId = item.id;
2499
- if (isUsable(itemId) === false) {
2500
- return;
2501
- }
2502
- const changes = getObjectChanges(oldItem, item);
2503
- if (Object.keys(changes).length === 0) {
1686
+ if (isUsable(mutation.error) === false) {
2504
1687
  return;
2505
1688
  }
2506
- supabase.schema("core").from("OperationLog").select().filter("tableName", "eq", tableName).filter("recordId", "eq", itemId).order("changeAt", {
2507
- ascending: false
2508
- }).limit(1).single().then((x) => {
2509
- if (isUsable(x.data) === false) {
2510
- return;
2511
- }
2512
- const data = x.data;
2513
- if (data.sessionId === UserSessionId) {
2514
- return;
2515
- }
2516
- const changeLog_0 = {
2517
- modifiedByUserId: data.changeBy,
2518
- changedOn: import_moment.default.utc(data.changeAt),
2519
- changes
2520
- };
2521
- setChangeLog(changeLog_0);
1689
+ toast.toast({
1690
+ title: "Error",
1691
+ description: mutation.error.message
2522
1692
  });
2523
- setOldItem(item);
2524
1693
  };
2525
- $[0] = item;
2526
- $[1] = oldItem;
2527
- $[2] = supabase;
2528
- $[3] = tableName;
2529
- $[4] = t0;
1694
+ $[0] = mutation.error;
1695
+ $[1] = toast;
1696
+ $[2] = t0;
2530
1697
  } else {
2531
- t0 = $[4];
1698
+ t0 = $[2];
2532
1699
  }
2533
1700
  let t1;
2534
- if ($[5] !== item) {
2535
- t1 = [item];
2536
- $[5] = item;
2537
- $[6] = t1;
1701
+ if ($[3] !== mutation.error) {
1702
+ t1 = [mutation.error];
1703
+ $[3] = mutation.error;
1704
+ $[4] = t1;
2538
1705
  } else {
2539
- t1 = $[6];
1706
+ t1 = $[4];
2540
1707
  }
2541
- useEffect4(t0, t1);
2542
- let t2;
2543
- if ($[7] !== action || $[8] !== changeLog) {
2544
- t2 = () => {
2545
- if (isUsable(changeLog) && action) {
2546
- action(changeLog.changes, changeLog);
1708
+ useEffect5(t0, t1);
1709
+ return mutation;
1710
+ }
1711
+
1712
+ // src/advance-query.tsx
1713
+ async function executeAdvanceQuery(supabase, query, filterLayer) {
1714
+ const parser = new PostgrestParser(query);
1715
+ const filterGroup = {
1716
+ id: filterLayer.id,
1717
+ op: filterLayer.op,
1718
+ not: filterLayer.not,
1719
+ filters: filterLayer.filters.map(normalizeFilter).filter((f) => f !== null)
1720
+ };
1721
+ const pagination = {
1722
+ offset: void 0,
1723
+ limit: void 0
1724
+ };
1725
+ const sort = [...filterLayer.sort || []];
1726
+ const searchParams = Array.from(parser.searchParams.entries());
1727
+ searchParams.forEach(([k, v]) => {
1728
+ if (k.includes("offset")) {
1729
+ pagination.offset = Number(v);
1730
+ return;
1731
+ }
1732
+ if (k.includes("limit")) {
1733
+ pagination.limit = Number(v);
1734
+ return;
1735
+ }
1736
+ if (k.includes("order")) {
1737
+ const orderColumns = v.split(",");
1738
+ orderColumns.forEach((x) => {
1739
+ const values2 = x.split(".");
1740
+ sort.push({
1741
+ field: values2[0],
1742
+ direction: values2[1] === "asc" ? "asc" : "desc"
1743
+ });
1744
+ });
1745
+ return;
1746
+ }
1747
+ if (v.includes(".") === false) return;
1748
+ const values = v.split(".");
1749
+ const column = k;
1750
+ const rawCondition = values[0];
1751
+ let condition = "";
1752
+ const value = values[1];
1753
+ if (column == "select") return;
1754
+ switch (rawCondition) {
1755
+ case "eq":
1756
+ condition = "=";
1757
+ break;
1758
+ case "in":
1759
+ condition = "in";
1760
+ break;
1761
+ case "lt":
1762
+ condition = "<";
1763
+ break;
1764
+ case "gt":
1765
+ condition = ">";
1766
+ break;
1767
+ case "lte":
1768
+ condition = "<=";
1769
+ break;
1770
+ case "gte":
1771
+ condition = ">=";
1772
+ break;
1773
+ case "is":
1774
+ condition = "is";
1775
+ break;
1776
+ case "ilike":
1777
+ condition = "ilike";
1778
+ break;
1779
+ case "neq":
1780
+ condition = "=";
1781
+ break;
1782
+ case "like":
1783
+ condition = "contains";
1784
+ break;
1785
+ }
1786
+ filterGroup.filters.push({
1787
+ id: `filter_${column}_${Date.now()}`,
1788
+ field: column,
1789
+ op: condition,
1790
+ value,
1791
+ display: `${column} ${condition} ${value}`
1792
+ });
1793
+ });
1794
+ const stripUIProperties = (obj) => {
1795
+ return JSON.parse(JSON.stringify(obj, (key, value) => {
1796
+ if (key === "display" || key === "info" || key === "options") {
1797
+ return void 0;
2547
1798
  }
1799
+ return value;
1800
+ }));
1801
+ };
1802
+ const cleanedBody = stripUIProperties({
1803
+ table: parser.table,
1804
+ schema: parser.schema,
1805
+ select: parser.select,
1806
+ filters: filterGroup,
1807
+ pagination,
1808
+ sort,
1809
+ count: "exact"
1810
+ });
1811
+ const response = await supabase.functions.invoke("query", {
1812
+ body: cleanedBody,
1813
+ method: "POST"
1814
+ });
1815
+ if (response.error) {
1816
+ return {
1817
+ data: null,
1818
+ count: null,
1819
+ error: response.error
2548
1820
  };
2549
- $[7] = action;
2550
- $[8] = changeLog;
2551
- $[9] = t2;
2552
- } else {
2553
- t2 = $[9];
2554
- }
2555
- let t3;
2556
- if ($[10] !== changeLog) {
2557
- t3 = [changeLog];
2558
- $[10] = changeLog;
2559
- $[11] = t3;
2560
- } else {
2561
- t3 = $[11];
2562
1821
  }
2563
- useEffect4(t2, t3);
2564
- return changeLog;
1822
+ return {
1823
+ data: response.data?.data ?? null,
1824
+ count: response.data?.count ?? null,
1825
+ error: null
1826
+ };
2565
1827
  }
2566
1828
 
2567
- // src/useLatestOperationLog.ts
2568
- import { c as _c13 } from "react/compiler-runtime";
2569
- function useLatestOperationLog(tableName, recordId) {
2570
- const $ = _c13(8);
1829
+ // src/storage/useStorageUrl.ts
1830
+ var import_moment2 = __toESM(require_moment(), 1);
1831
+ import { useRef as useRef4 } from "react";
1832
+ import { useIndexedDB } from "@pol-studios/hooks/storage";
1833
+ var cacheVersions = /* @__PURE__ */ new Map();
1834
+ var cacheVersionListeners = /* @__PURE__ */ new Map();
1835
+ var retryAttempts = /* @__PURE__ */ new Map();
1836
+ function useStorageUrl() {
1837
+ const db = useIndexedDB({
1838
+ dbName: "polstudios",
1839
+ storeName: "cached-urls"
1840
+ });
1841
+ const storedUrls = useRef4(/* @__PURE__ */ new Map());
2571
1842
  const supabase = useSupabase();
2572
- const t0 = supabase;
2573
- let t1;
2574
- if ($[0] !== recordId || $[1] !== t0 || $[2] !== tableName) {
2575
- t1 = t0.schema("core").from("OperationLog").select(OperationLog.defaultQuery).eq("recordId", String(recordId)).eq("tableName", tableName).order("changeAt", {
2576
- ascending: false
2577
- }).limit(1).maybeSingle();
2578
- $[0] = recordId;
2579
- $[1] = t0;
2580
- $[2] = tableName;
2581
- $[3] = t1;
2582
- } else {
2583
- t1 = $[3];
2584
- }
2585
- let t2;
2586
- if ($[4] !== recordId) {
2587
- t2 = isUsable(recordId);
2588
- $[4] = recordId;
2589
- $[5] = t2;
2590
- } else {
2591
- t2 = $[5];
1843
+ function getCacheVersion(entity) {
1844
+ const key = `${entity.bucketId}${entity.path}`;
1845
+ return cacheVersions.get(key) || 0;
2592
1846
  }
2593
- let t3;
2594
- if ($[6] !== t2) {
2595
- t3 = {
2596
- refetchOnMount: true,
2597
- refetchOnWindowFocus: true,
2598
- staleTime: 0,
2599
- enabled: t2
1847
+ function subscribeToCacheVersion(entity_0, callback) {
1848
+ const key_0 = `${entity_0.bucketId}${entity_0.path}`;
1849
+ if (!cacheVersionListeners.has(key_0)) {
1850
+ cacheVersionListeners.set(key_0, /* @__PURE__ */ new Set());
1851
+ }
1852
+ cacheVersionListeners.get(key_0).add(callback);
1853
+ return () => {
1854
+ cacheVersionListeners.get(key_0)?.delete(callback);
2600
1855
  };
2601
- $[6] = t2;
2602
- $[7] = t3;
2603
- } else {
2604
- t3 = $[7];
2605
1856
  }
2606
- return useDbQuery(t1, t3);
2607
- }
2608
-
2609
- // src/useAutosaveState.ts
2610
- import { useCallback as useCallback2, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef5, useState as useState5 } from "react";
2611
- function newTimeActivity(date) {
2612
- return {
2613
- activityDate: date.clone().startOf("day").toISOString(true),
2614
- description: "",
2615
- hasRequestBillableChange: false,
2616
- hasRequestVerification: false,
2617
- hours: 0,
2618
- userNotes: "",
2619
- adminNotes: "",
2620
- userId: null,
2621
- clientId: null,
2622
- projectId: null,
2623
- workingPhaseId: null,
2624
- roleId: null,
2625
- taskId: null,
2626
- subtaskId: null,
2627
- weeklyTimesheetId: null,
2628
- id: null,
2629
- BillingDetails: {
2630
- status: "Unknown",
2631
- id: null,
2632
- orderHint: "",
2633
- chargeTableId: null,
2634
- cosmosId: null,
2635
- amount: 0,
2636
- rate: 0,
2637
- type: "TimeActivity"
2638
- }
2639
- };
2640
- }
2641
- function getNewValue(action, prevState) {
2642
- return typeof action === "function" ? action(prevState) : action;
2643
- }
2644
- function useAutosaveState(relation, defaultValue, options) {
2645
- const [value, setValue] = useState5(() => defaultValue);
2646
- const [baseValue, setBaseValue] = useState5(() => defaultValue);
2647
- const baseValueRef = useRef5(defaultValue);
2648
- const pendingChangesRef = useRef5(/* @__PURE__ */ new Map());
2649
- const currentId = useRef5(null);
2650
- const newOptions = useMemo4(() => options ? {
2651
- ...options,
2652
- primaryKeys: options.primaryKeys ?? ["id"]
2653
- } : {
2654
- delay: 200,
2655
- primaryKeys: ["id"]
2656
- }, [options]);
2657
- const upsertMutation = useDbUpsert(relation, {
2658
- invalidateTables: [relation]
2659
- });
2660
- const saveEntityChanges = useCallback2(async (entityId) => {
2661
- if (__DEV__) {
2662
- console.log("[Autosave] saveEntityChanges called:", {
2663
- entityId,
2664
- relation,
2665
- hasPendingEntry: pendingChangesRef.current.has(entityId)
1857
+ async function expireCache(entity_1) {
1858
+ const key_1 = `${entity_1.bucketId}${entity_1.path}`;
1859
+ const dbKeys = await db.getAllKeys();
1860
+ const keysToDelete = Array.from(new Set([...Array.from(storedUrls.current.keys()), ...dbKeys].filter((value) => value.startsWith(key_1))));
1861
+ await Promise.all(keysToDelete.map(async (x) => {
1862
+ storedUrls.current.delete(x);
1863
+ await db.removeItem(x);
1864
+ }));
1865
+ const currentVersion = cacheVersions.get(key_1) || 0;
1866
+ cacheVersions.set(key_1, currentVersion + 1);
1867
+ const listeners = cacheVersionListeners.get(key_1);
1868
+ if (listeners) {
1869
+ listeners.forEach((callback_0) => {
1870
+ callback_0();
2666
1871
  });
2667
1872
  }
2668
- const pending = pendingChangesRef.current.get(entityId);
2669
- if (!pending) {
2670
- if (__DEV__) {
2671
- console.log("[Autosave] No pending changes found for entity:", entityId);
2672
- }
1873
+ }
1874
+ async function baseFetchUrl(entity_2, options, isPublic = false) {
1875
+ if (isUsable(entity_2) === false) return;
1876
+ const optionsString = JSON.stringify(options);
1877
+ if (isUsable(entity_2.bucketId) === false) {
2673
1878
  return;
2674
1879
  }
2675
- const changes = diff(pending.baseValue, pending.currentValue);
2676
- if (__DEV__) {
2677
- console.log("[Autosave] Computed diff:", {
2678
- entityId,
2679
- relation,
2680
- changeKeys: Object.keys(changes),
2681
- changes,
2682
- baseValue: pending.baseValue,
2683
- currentValue: pending.currentValue
2684
- });
1880
+ if (isUsable(entity_2.path) === false) {
1881
+ return;
2685
1882
  }
2686
- if (Object.keys(changes).length === 0) {
2687
- if (__DEV__) {
2688
- console.log("[Autosave] No changes detected, skipping save for:", entityId);
1883
+ const key_2 = `${entity_2.bucketId}${entity_2.path}${optionsString ?? ""}-cached-url`;
1884
+ const inMemoryItem = storedUrls.current.get(key_2);
1885
+ let item = inMemoryItem;
1886
+ if (isUsable(inMemoryItem) === false) {
1887
+ item = await db.getItem(key_2) ?? void 0;
1888
+ if (isUsable(item)) {
1889
+ }
1890
+ } else {
1891
+ }
1892
+ if (isUsable(item) && (0, import_moment2.default)(item.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
1893
+ return item.url;
1894
+ }
1895
+ const base = supabase.storage.from(entity_2.bucketId);
1896
+ let download = options?.download;
1897
+ if (typeof options?.download === "string") {
1898
+ const ext = entity_2.path.split(".").pop() ?? "";
1899
+ download = options?.download.endsWith(ext) ? options?.download : options?.download + "." + ext;
1900
+ }
1901
+ const newOptions = options ? {
1902
+ ...options,
1903
+ download
1904
+ } : void 0;
1905
+ const retryKey = `${entity_2.bucketId}/${entity_2.path}`;
1906
+ const currentRetries = retryAttempts.get(retryKey) || 0;
1907
+ let url;
1908
+ if (isPublic) {
1909
+ url = base.getPublicUrl(entity_2.path, newOptions).data.publicUrl;
1910
+ } else {
1911
+ try {
1912
+ console.log("Creating signed URL for", entity_2.path);
1913
+ const result = await base.createSignedUrl(entity_2.path, 60 * 100, newOptions);
1914
+ url = result.data?.signedUrl;
1915
+ if (isUsable(url)) {
1916
+ retryAttempts.delete(retryKey);
1917
+ } else if (currentRetries < 3) {
1918
+ retryAttempts.set(retryKey, currentRetries + 1);
1919
+ throw new Error("Failed to get signed URL");
1920
+ }
1921
+ } catch (error) {
1922
+ if (currentRetries < 3) {
1923
+ retryAttempts.set(retryKey, currentRetries + 1);
1924
+ const delay = Math.min(1e3 * Math.pow(2, currentRetries), 5e3);
1925
+ await new Promise((resolve) => setTimeout(resolve, delay));
1926
+ return baseFetchUrl(entity_2, options, isPublic);
1927
+ }
1928
+ retryAttempts.delete(retryKey);
1929
+ return void 0;
2689
1930
  }
2690
- pendingChangesRef.current.delete(entityId);
2691
- return;
2692
1931
  }
2693
- const patch = {
2694
- ...changes,
2695
- id: entityId
1932
+ if (isUsable(url) === false) return url;
1933
+ const cachedUrl = {
1934
+ key: key_2,
1935
+ url,
1936
+ expiresOn: (0, import_moment2.default)().add(60 * 100, "seconds").toISOString(true)
2696
1937
  };
2697
- const finalPatch = newOptions.transformBeforeMutation ? newOptions.transformBeforeMutation(patch) : patch;
2698
- if (__DEV__) {
2699
- console.log("[Autosave] Calling mutateAsync:", {
2700
- entityId,
2701
- relation,
2702
- patch,
2703
- finalPatch,
2704
- hasTransform: !!newOptions.transformBeforeMutation
2705
- });
1938
+ storedUrls.current.set(key_2, cachedUrl);
1939
+ db.setItem(key_2, cachedUrl);
1940
+ return url;
1941
+ }
1942
+ async function fetchUrl(entity_3, options_0) {
1943
+ return baseFetchUrl(entity_3, options_0, false);
1944
+ }
1945
+ async function fetchPublicUrl(entity_4, options_1) {
1946
+ return baseFetchUrl(entity_4, options_1, true);
1947
+ }
1948
+ async function prefetchImage(entity_5, options_2) {
1949
+ const url_0 = await fetchUrl(entity_5, options_2);
1950
+ if (url_0) {
1951
+ new Image().src = url_0;
2706
1952
  }
2707
- try {
2708
- const result = await upsertMutation.mutateAsync(finalPatch);
2709
- if (__DEV__) {
2710
- console.log("[Autosave] mutateAsync SUCCESS:", {
2711
- entityId,
2712
- relation,
2713
- finalPatch,
2714
- result
2715
- });
2716
- }
2717
- pendingChangesRef.current.delete(entityId);
2718
- } catch (error) {
2719
- if (__DEV__) {
2720
- console.error("[Autosave] mutateAsync FAILED:", {
2721
- entityId,
2722
- relation,
2723
- finalPatch,
2724
- error,
2725
- errorMessage: error instanceof Error ? error.message : String(error),
2726
- errorStack: error instanceof Error ? error.stack : void 0
2727
- });
2728
- }
2729
- throw error;
1953
+ }
1954
+ async function fetchUrls(entities, options_3) {
1955
+ const results = /* @__PURE__ */ new Map();
1956
+ if (entities.length === 0) return results;
1957
+ const optionsString_0 = JSON.stringify(options_3);
1958
+ const expirySeconds = 60 * 100;
1959
+ const byBucket = /* @__PURE__ */ new Map();
1960
+ for (const entity_6 of entities) {
1961
+ if (!isUsable(entity_6.bucketId) || !isUsable(entity_6.path)) continue;
1962
+ const list = byBucket.get(entity_6.bucketId) ?? [];
1963
+ list.push(entity_6);
1964
+ byBucket.set(entity_6.bucketId, list);
2730
1965
  }
2731
- }, [relation, upsertMutation, newOptions.transformBeforeMutation]);
2732
- const updateValue = useCallback2((update) => {
2733
- setValue((prev) => {
2734
- const newValue = getNewValue(update, prev);
2735
- const entityId_0 = newValue.id;
2736
- if (!entityId_0) return newValue;
2737
- let pending_0 = pendingChangesRef.current.get(entityId_0);
2738
- if (!pending_0) {
2739
- pending_0 = {
2740
- baseValue: baseValueRef.current,
2741
- currentValue: newValue,
2742
- timeoutId: null
2743
- };
2744
- pendingChangesRef.current.set(entityId_0, pending_0);
2745
- if (__DEV__) {
2746
- console.log("[Autosave] Created new pending entry using baseValueRef:", {
2747
- entityId: entityId_0,
2748
- baseValueId: baseValueRef.current?.id
2749
- });
1966
+ for (const [bucketId, bucketEntities] of byBucket) {
1967
+ const uncached = [];
1968
+ for (const entity_7 of bucketEntities) {
1969
+ const key_3 = `${entity_7.bucketId}${entity_7.path}${optionsString_0 ?? ""}-cached-url`;
1970
+ const entityKey = `${entity_7.bucketId}/${entity_7.path}`;
1971
+ let item_0 = storedUrls.current.get(key_3);
1972
+ if (!isUsable(item_0)) {
1973
+ item_0 = await db.getItem(key_3) ?? void 0;
1974
+ }
1975
+ if (isUsable(item_0) && (0, import_moment2.default)(item_0.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
1976
+ results.set(entityKey, item_0.url);
1977
+ } else {
1978
+ uncached.push(entity_7);
2750
1979
  }
2751
- } else {
2752
- pending_0.currentValue = newValue;
2753
1980
  }
2754
- if (pending_0.timeoutId) {
2755
- clearTimeout(pending_0.timeoutId);
1981
+ if (uncached.length > 0) {
1982
+ const paths = uncached.map((e) => e.path);
1983
+ const base_0 = supabase.storage.from(bucketId);
1984
+ try {
1985
+ console.log("Signed URLs created");
1986
+ const {
1987
+ data,
1988
+ error: error_0
1989
+ } = await base_0.createSignedUrls(paths, expirySeconds);
1990
+ if (!error_0 && data) {
1991
+ const expiresOn = (0, import_moment2.default)().add(expirySeconds, "seconds").toISOString(true);
1992
+ for (let i = 0; i < uncached.length; i++) {
1993
+ const entity_9 = uncached[i];
1994
+ const urlData = data[i];
1995
+ const entityKey_1 = `${entity_9.bucketId}/${entity_9.path}`;
1996
+ const cacheKey = `${entity_9.bucketId}${entity_9.path}${optionsString_0 ?? ""}-cached-url`;
1997
+ if (urlData?.signedUrl) {
1998
+ results.set(entityKey_1, urlData.signedUrl);
1999
+ const cachedUrl_0 = {
2000
+ key: cacheKey,
2001
+ url: urlData.signedUrl,
2002
+ expiresOn
2003
+ };
2004
+ storedUrls.current.set(cacheKey, cachedUrl_0);
2005
+ db.setItem(cacheKey, cachedUrl_0);
2006
+ } else {
2007
+ results.set(entityKey_1, void 0);
2008
+ }
2009
+ }
2010
+ } else {
2011
+ for (const entity_10 of uncached) {
2012
+ const entityKey_2 = `${entity_10.bucketId}/${entity_10.path}`;
2013
+ const url_2 = await fetchUrl(entity_10, options_3);
2014
+ results.set(entityKey_2, url_2);
2015
+ }
2016
+ }
2017
+ } catch {
2018
+ for (const entity_8 of uncached) {
2019
+ const entityKey_0 = `${entity_8.bucketId}/${entity_8.path}`;
2020
+ const url_1 = await fetchUrl(entity_8, options_3);
2021
+ results.set(entityKey_0, url_1);
2022
+ }
2023
+ }
2756
2024
  }
2757
- pending_0.timeoutId = setTimeout(() => {
2758
- saveEntityChanges(entityId_0);
2759
- }, newOptions.delay);
2760
- return newValue;
2761
- });
2762
- }, [saveEntityChanges, newOptions.delay]);
2763
- const setNewEntity = useCallback2((newEntity) => {
2764
- baseValueRef.current = newEntity;
2765
- if (__DEV__) {
2766
- console.log("[Autosave] setNewEntity - baseValueRef updated synchronously:", {
2767
- entityId: newEntity.id,
2768
- relation
2769
- });
2770
- }
2771
- setValue(newEntity);
2772
- setBaseValue(newEntity);
2773
- currentId.current = newEntity.id;
2774
- }, [relation]);
2775
- useEffect5(() => {
2776
- return () => {
2777
- pendingChangesRef.current.forEach((pending_1) => {
2778
- if (pending_1.timeoutId) clearTimeout(pending_1.timeoutId);
2779
- });
2780
- };
2781
- }, []);
2782
- const saveCurrentValue = useCallback2(async () => {
2783
- if (currentId.current) {
2784
- await saveEntityChanges(currentId.current);
2785
2025
  }
2786
- }, [saveEntityChanges]);
2787
- return [value, updateValue, upsertMutation, setValue, setNewEntity, saveCurrentValue];
2026
+ return results;
2027
+ }
2028
+ return {
2029
+ fetchUrl,
2030
+ fetchUrls,
2031
+ prefetchImage,
2032
+ fetchPublicUrl,
2033
+ expireCache,
2034
+ getCacheVersion,
2035
+ subscribeToCacheVersion
2036
+ };
2788
2037
  }
2789
2038
 
2790
- // src/useToastError.ts
2791
- import { c as _c14 } from "react/compiler-runtime";
2792
- import { useEffect as useEffect6 } from "react";
2793
- import { useToast } from "@pol-studios/hooks/toast";
2794
- function useToastError(mutation) {
2795
- const $ = _c14(5);
2796
- const toast = useToast();
2797
- let t0;
2798
- if ($[0] !== mutation.error || $[1] !== toast) {
2799
- t0 = () => {
2800
- if (isUsable(mutation.error) === false) {
2039
+ // src/storage/useStoragePath.ts
2040
+ import { c as _c6 } from "react/compiler-runtime";
2041
+ import { useEffect as useEffect6, useState as useState4 } from "react";
2042
+ function getContentType(metadata, path) {
2043
+ if (metadata?.contentType) {
2044
+ return metadata.contentType;
2045
+ }
2046
+ const ext = path.split(".").pop()?.toUpperCase();
2047
+ return ext || "Unknown";
2048
+ }
2049
+ function useStoragePath(storagePath, bucketId, t0) {
2050
+ const $ = _c6(40);
2051
+ let t1;
2052
+ if ($[0] !== t0) {
2053
+ t1 = t0 === void 0 ? {} : t0;
2054
+ $[0] = t0;
2055
+ $[1] = t1;
2056
+ } else {
2057
+ t1 = $[1];
2058
+ }
2059
+ const options = t1;
2060
+ const {
2061
+ fetchMetadata: t2,
2062
+ transform,
2063
+ download
2064
+ } = options;
2065
+ const fetchMetadata = t2 === void 0 ? true : t2;
2066
+ const [url, setUrl] = useState4(null);
2067
+ const [error, setError] = useState4(null);
2068
+ const {
2069
+ fetchUrl
2070
+ } = useStorageUrl();
2071
+ const supabase = useSupabase();
2072
+ let t3;
2073
+ if ($[2] !== bucketId || $[3] !== download || $[4] !== fetchUrl || $[5] !== storagePath || $[6] !== transform) {
2074
+ t3 = () => {
2075
+ if (!isUsable(storagePath) || !isUsable(bucketId)) {
2076
+ setUrl(null);
2801
2077
  return;
2802
2078
  }
2803
- toast.toast({
2804
- title: "Error",
2805
- description: mutation.error.message
2079
+ let cancelled = false;
2080
+ fetchUrl({
2081
+ bucketId,
2082
+ path: storagePath
2083
+ }, {
2084
+ transform,
2085
+ download
2086
+ }).then((signedUrl) => {
2087
+ if (!cancelled) {
2088
+ setUrl(signedUrl ?? null);
2089
+ setError(null);
2090
+ }
2091
+ }).catch((err) => {
2092
+ if (!cancelled) {
2093
+ setError(err instanceof Error ? err : new Error(String(err)));
2094
+ setUrl(null);
2095
+ }
2806
2096
  });
2097
+ return () => {
2098
+ cancelled = true;
2099
+ };
2807
2100
  };
2808
- $[0] = mutation.error;
2809
- $[1] = toast;
2810
- $[2] = t0;
2101
+ $[2] = bucketId;
2102
+ $[3] = download;
2103
+ $[4] = fetchUrl;
2104
+ $[5] = storagePath;
2105
+ $[6] = transform;
2106
+ $[7] = t3;
2811
2107
  } else {
2812
- t0 = $[2];
2108
+ t3 = $[7];
2813
2109
  }
2814
- let t1;
2815
- if ($[3] !== mutation.error) {
2816
- t1 = [mutation.error];
2817
- $[3] = mutation.error;
2818
- $[4] = t1;
2110
+ let t4;
2111
+ if ($[8] !== transform) {
2112
+ t4 = JSON.stringify(transform);
2113
+ $[8] = transform;
2114
+ $[9] = t4;
2819
2115
  } else {
2820
- t1 = $[4];
2116
+ t4 = $[9];
2821
2117
  }
2822
- useEffect6(t0, t1);
2823
- return mutation;
2118
+ let t5;
2119
+ if ($[10] !== bucketId || $[11] !== download || $[12] !== storagePath || $[13] !== t4) {
2120
+ t5 = [storagePath, bucketId, t4, download];
2121
+ $[10] = bucketId;
2122
+ $[11] = download;
2123
+ $[12] = storagePath;
2124
+ $[13] = t4;
2125
+ $[14] = t5;
2126
+ } else {
2127
+ t5 = $[14];
2128
+ }
2129
+ useEffect6(t3, t5);
2130
+ let t6;
2131
+ if ($[15] !== bucketId || $[16] !== storagePath || $[17] !== supabase) {
2132
+ t6 = supabase.schema("storage").from("objects").select("metadata").eq("bucket_id", bucketId).eq("name", storagePath ?? "").maybeSingle();
2133
+ $[15] = bucketId;
2134
+ $[16] = storagePath;
2135
+ $[17] = supabase;
2136
+ $[18] = t6;
2137
+ } else {
2138
+ t6 = $[18];
2139
+ }
2140
+ const storageQuery = t6;
2141
+ let t7;
2142
+ if ($[19] !== bucketId || $[20] !== fetchMetadata || $[21] !== storagePath) {
2143
+ t7 = fetchMetadata && isUsable(storagePath) && isUsable(bucketId);
2144
+ $[19] = bucketId;
2145
+ $[20] = fetchMetadata;
2146
+ $[21] = storagePath;
2147
+ $[22] = t7;
2148
+ } else {
2149
+ t7 = $[22];
2150
+ }
2151
+ let t8;
2152
+ if ($[23] !== t7) {
2153
+ t8 = {
2154
+ enabled: t7
2155
+ };
2156
+ $[23] = t7;
2157
+ $[24] = t8;
2158
+ } else {
2159
+ t8 = $[24];
2160
+ }
2161
+ const metadataRequest = useDbQuery(storageQuery, t8);
2162
+ const metadata = metadataRequest.data?.metadata ?? null;
2163
+ const t9 = storagePath ?? "";
2164
+ let t10;
2165
+ if ($[25] !== metadata || $[26] !== t9) {
2166
+ t10 = getContentType(metadata, t9);
2167
+ $[25] = metadata;
2168
+ $[26] = t9;
2169
+ $[27] = t10;
2170
+ } else {
2171
+ t10 = $[27];
2172
+ }
2173
+ const contentType = t10;
2174
+ let t11;
2175
+ if ($[28] !== error || $[29] !== fetchMetadata || $[30] !== metadataRequest.isFetching || $[31] !== storagePath || $[32] !== url) {
2176
+ t11 = isUsable(storagePath) && url === null && error === null || fetchMetadata && metadataRequest.isFetching;
2177
+ $[28] = error;
2178
+ $[29] = fetchMetadata;
2179
+ $[30] = metadataRequest.isFetching;
2180
+ $[31] = storagePath;
2181
+ $[32] = url;
2182
+ $[33] = t11;
2183
+ } else {
2184
+ t11 = $[33];
2185
+ }
2186
+ const isLoading = t11;
2187
+ let t12;
2188
+ if ($[34] !== contentType || $[35] !== error || $[36] !== isLoading || $[37] !== metadata || $[38] !== url) {
2189
+ t12 = {
2190
+ url,
2191
+ metadata,
2192
+ contentType,
2193
+ isLoading,
2194
+ error
2195
+ };
2196
+ $[34] = contentType;
2197
+ $[35] = error;
2198
+ $[36] = isLoading;
2199
+ $[37] = metadata;
2200
+ $[38] = url;
2201
+ $[39] = t12;
2202
+ } else {
2203
+ t12 = $[39];
2204
+ }
2205
+ return t12;
2824
2206
  }
2825
2207
 
2826
- // src/advance-query.tsx
2827
- async function executeAdvanceQuery(supabase, query, filterLayer) {
2828
- const parser = new PostgrestParser(query);
2829
- const filterGroup = {
2830
- id: filterLayer.id,
2831
- op: filterLayer.op,
2832
- not: filterLayer.not,
2833
- filters: filterLayer.filters.map(normalizeFilter).filter((f) => f !== null)
2834
- };
2835
- const pagination = {
2836
- offset: void 0,
2837
- limit: void 0
2838
- };
2839
- const sort = [...filterLayer.sort || []];
2840
- const searchParams = Array.from(parser.searchParams.entries());
2841
- searchParams.forEach(([k, v]) => {
2842
- if (k.includes("offset")) {
2843
- pagination.offset = Number(v);
2844
- return;
2845
- }
2846
- if (k.includes("limit")) {
2847
- pagination.limit = Number(v);
2848
- return;
2849
- }
2850
- if (k.includes("order")) {
2851
- const orderColumns = v.split(",");
2852
- orderColumns.forEach((x) => {
2853
- const values2 = x.split(".");
2854
- sort.push({
2855
- field: values2[0],
2856
- direction: values2[1] === "asc" ? "asc" : "desc"
2857
- });
2858
- });
2208
+ // src/storage/bucketConfig.ts
2209
+ var BUCKETS = {
2210
+ AVATARS: "avatars",
2211
+ FIXTURE_CATALOG_COVER: "fixture-catalog-cover",
2212
+ FIXTURE_ATTACHMENTS: "fixture-attachments",
2213
+ UNIT_DOCUMENTATION: "unit-documentation-attachments",
2214
+ DATASHEETS: "datasheets",
2215
+ PATTERNS: "patterns",
2216
+ LOGOS: "logos",
2217
+ RECEIPTS: "receipts",
2218
+ TICKET_ATTACHMENTS: "ticket-attachment",
2219
+ PROCESS_RESULTS: "process-results",
2220
+ DATA_EXCHANGE_IMPORTS: "data-exchange-imports",
2221
+ EMAIL_TEMPLATES: "email-templates",
2222
+ EMAIL_TEMPLATES_ASSETS: "email-templates-assets"
2223
+ };
2224
+
2225
+ // src/utilities/query-utils.ts
2226
+ function createInCondition(column, values) {
2227
+ let condition = "";
2228
+ if (values.length > 2e3) {
2229
+ throw new Error("Too many values to create in condition");
2230
+ }
2231
+ chunkArray(values, 99).forEach((x, index) => {
2232
+ if (index == 0) {
2233
+ condition = `${column}.in.(${x.join(",")})`;
2859
2234
  return;
2860
2235
  }
2861
- if (v.includes(".") === false) return;
2862
- const values = v.split(".");
2863
- const column = k;
2864
- const rawCondition = values[0];
2865
- let condition = "";
2866
- const value = values[1];
2867
- if (column == "select") return;
2868
- switch (rawCondition) {
2869
- case "eq":
2870
- condition = "=";
2871
- break;
2872
- case "in":
2873
- condition = "in";
2874
- break;
2875
- case "lt":
2876
- condition = "<";
2877
- break;
2878
- case "gt":
2879
- condition = ">";
2880
- break;
2881
- case "lte":
2882
- condition = "<=";
2883
- break;
2884
- case "gte":
2885
- condition = ">=";
2886
- break;
2887
- case "is":
2888
- condition = "is";
2889
- break;
2890
- case "ilike":
2891
- condition = "ilike";
2892
- break;
2893
- case "neq":
2894
- condition = "=";
2895
- break;
2896
- case "like":
2897
- condition = "contains";
2898
- break;
2899
- }
2900
- filterGroup.filters.push({
2901
- id: `filter_${column}_${Date.now()}`,
2902
- field: column,
2903
- op: condition,
2904
- value,
2905
- display: `${column} ${condition} ${value}`
2906
- });
2236
+ condition += `,${column}.in.(${x.join(",")})`;
2907
2237
  });
2908
- const stripUIProperties = (obj) => {
2909
- return JSON.parse(JSON.stringify(obj, (key, value) => {
2910
- if (key === "display" || key === "info" || key === "options") {
2911
- return void 0;
2238
+ return condition;
2239
+ }
2240
+
2241
+ // src/useDbDelete.ts
2242
+ import { c as _c7 } from "react/compiler-runtime";
2243
+ import { useMutation } from "@tanstack/react-query";
2244
+ function useDbDelete(relation, t0) {
2245
+ const $ = _c7(14);
2246
+ let t1;
2247
+ if ($[0] !== t0) {
2248
+ t1 = t0 === void 0 ? ["id"] : t0;
2249
+ $[0] = t0;
2250
+ $[1] = t1;
2251
+ } else {
2252
+ t1 = $[1];
2253
+ }
2254
+ const primaryKeys = t1;
2255
+ const tableName = typeof relation === "object" ? relation.table : relation;
2256
+ const schemaName = typeof relation === "object" ? relation.schema : "public";
2257
+ const supabase = useSupabase();
2258
+ let t2;
2259
+ if ($[2] !== primaryKeys) {
2260
+ t2 = primaryKeys.map(_temp);
2261
+ $[2] = primaryKeys;
2262
+ $[3] = t2;
2263
+ } else {
2264
+ t2 = $[3];
2265
+ }
2266
+ const t3 = t2;
2267
+ let t4;
2268
+ if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
2269
+ t4 = {
2270
+ primaryKeys: t3,
2271
+ table: tableName,
2272
+ schema: schemaName
2273
+ };
2274
+ $[4] = schemaName;
2275
+ $[5] = t3;
2276
+ $[6] = tableName;
2277
+ $[7] = t4;
2278
+ } else {
2279
+ t4 = $[7];
2280
+ }
2281
+ const deleteItem = useDeleteItem(t4);
2282
+ let t5;
2283
+ if ($[8] !== deleteItem || $[9] !== primaryKeys || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
2284
+ t5 = {
2285
+ mutationFn: async (item) => {
2286
+ if (Array.isArray(item)) {
2287
+ throw new Error("Item cannot be an array.");
2288
+ }
2289
+ const deleteQuery = supabase.schema(schemaName).from(tableName).delete();
2290
+ primaryKeys.forEach((key) => {
2291
+ const keyStr = String(key);
2292
+ const value = item[keyStr];
2293
+ if (isUsable(value)) {
2294
+ deleteQuery.eq(keyStr, value);
2295
+ }
2296
+ });
2297
+ const response = await deleteQuery.select().single();
2298
+ if (response.error) {
2299
+ throw response.error;
2300
+ }
2301
+ if (response.data) {
2302
+ deleteItem(response.data);
2303
+ } else {
2304
+ deleteItem(item);
2305
+ }
2306
+ return response.data;
2912
2307
  }
2913
- return value;
2914
- }));
2915
- };
2916
- const cleanedBody = stripUIProperties({
2917
- table: parser.table,
2918
- schema: parser.schema,
2919
- select: parser.select,
2920
- filters: filterGroup,
2921
- pagination,
2922
- sort,
2923
- count: "exact"
2924
- });
2925
- const response = await supabase.functions.invoke("query", {
2926
- body: cleanedBody,
2927
- method: "POST"
2928
- });
2929
- if (response.error) {
2930
- return {
2931
- data: null,
2932
- count: null,
2933
- error: response.error
2934
2308
  };
2309
+ $[8] = deleteItem;
2310
+ $[9] = primaryKeys;
2311
+ $[10] = schemaName;
2312
+ $[11] = supabase;
2313
+ $[12] = tableName;
2314
+ $[13] = t5;
2315
+ } else {
2316
+ t5 = $[13];
2935
2317
  }
2936
- return {
2937
- data: response.data?.data ?? null,
2938
- count: response.data?.count ?? null,
2939
- error: null
2940
- };
2318
+ const deleteMutation = useMutation(t5);
2319
+ return deleteMutation;
2320
+ }
2321
+ function _temp(k) {
2322
+ return String(k);
2941
2323
  }
2942
2324
 
2943
- // src/storage/useStorageUrl.ts
2944
- var import_moment2 = __toESM(require_moment(), 1);
2945
- import { useRef as useRef6 } from "react";
2946
- import { useIndexedDB } from "@pol-studios/hooks/storage";
2947
- var cacheVersions = /* @__PURE__ */ new Map();
2948
- var cacheVersionListeners = /* @__PURE__ */ new Map();
2949
- var retryAttempts = /* @__PURE__ */ new Map();
2950
- function useStorageUrl() {
2951
- const db = useIndexedDB({
2952
- dbName: "polstudios",
2953
- storeName: "cached-urls"
2954
- });
2955
- const storedUrls = useRef6(/* @__PURE__ */ new Map());
2956
- const supabase = useSupabase();
2957
- function getCacheVersion(entity) {
2958
- const key = `${entity.bucketId}${entity.path}`;
2959
- return cacheVersions.get(key) || 0;
2325
+ // src/useDbMultiUpsert.ts
2326
+ import { c as _c8 } from "react/compiler-runtime";
2327
+ import { useMutation as useMutation2 } from "@tanstack/react-query";
2328
+ function useDbMultiUpsert(relation, t0, t1) {
2329
+ const $ = _c8(17);
2330
+ let t2;
2331
+ if ($[0] !== t0) {
2332
+ t2 = t0 === void 0 ? ["id"] : t0;
2333
+ $[0] = t0;
2334
+ $[1] = t2;
2335
+ } else {
2336
+ t2 = $[1];
2960
2337
  }
2961
- function subscribeToCacheVersion(entity_0, callback) {
2962
- const key_0 = `${entity_0.bucketId}${entity_0.path}`;
2963
- if (!cacheVersionListeners.has(key_0)) {
2964
- cacheVersionListeners.set(key_0, /* @__PURE__ */ new Set());
2965
- }
2966
- cacheVersionListeners.get(key_0).add(callback);
2967
- return () => {
2968
- cacheVersionListeners.get(key_0)?.delete(callback);
2338
+ const primaryKeys = t2;
2339
+ const query = t1 === void 0 ? "*" : t1;
2340
+ const supabase = useSupabase();
2341
+ const tableName = typeof relation === "object" ? relation.table : relation;
2342
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
2343
+ const t3 = relation;
2344
+ let t4;
2345
+ if ($[2] !== primaryKeys || $[3] !== t3) {
2346
+ t4 = {
2347
+ primaryKeys,
2348
+ table: t3,
2349
+ schema: "public"
2969
2350
  };
2351
+ $[2] = primaryKeys;
2352
+ $[3] = t3;
2353
+ $[4] = t4;
2354
+ } else {
2355
+ t4 = $[4];
2970
2356
  }
2971
- async function expireCache(entity_1) {
2972
- const key_1 = `${entity_1.bucketId}${entity_1.path}`;
2973
- const dbKeys = await db.getAllKeys();
2974
- const keysToDelete = Array.from(new Set([...Array.from(storedUrls.current.keys()), ...dbKeys].filter((value) => value.startsWith(key_1))));
2975
- await Promise.all(keysToDelete.map(async (x) => {
2976
- storedUrls.current.delete(x);
2977
- await db.removeItem(x);
2978
- }));
2979
- const currentVersion = cacheVersions.get(key_1) || 0;
2980
- cacheVersions.set(key_1, currentVersion + 1);
2981
- const listeners = cacheVersionListeners.get(key_1);
2982
- if (listeners) {
2983
- listeners.forEach((callback_0) => {
2984
- callback_0();
2985
- });
2986
- }
2357
+ const upsertItem = useUpsertItem(t4);
2358
+ let t5;
2359
+ if ($[5] !== primaryKeys) {
2360
+ t5 = primaryKeys.map(_temp3);
2361
+ $[5] = primaryKeys;
2362
+ $[6] = t5;
2363
+ } else {
2364
+ t5 = $[6];
2987
2365
  }
2988
- async function baseFetchUrl(entity_2, options, isPublic = false) {
2989
- if (isUsable(entity_2) === false) return;
2990
- const optionsString = JSON.stringify(options);
2991
- if (isUsable(entity_2.bucketId) === false) {
2992
- return;
2993
- }
2994
- if (isUsable(entity_2.path) === false) {
2995
- return;
2996
- }
2997
- const key_2 = `${entity_2.bucketId}${entity_2.path}${optionsString ?? ""}-cached-url`;
2998
- const inMemoryItem = storedUrls.current.get(key_2);
2999
- let item = inMemoryItem;
3000
- if (isUsable(inMemoryItem) === false) {
3001
- item = await db.getItem(key_2) ?? void 0;
3002
- if (isUsable(item)) {
2366
+ const primaryKeysAsStrings = t5;
2367
+ let t6;
2368
+ if ($[7] !== primaryKeys || $[8] !== primaryKeysAsStrings || $[9] !== query || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
2369
+ t6 = async function upsertItemAction2(item) {
2370
+ let task;
2371
+ if (Object.keys(item).length !== primaryKeys.length && primaryKeys.every((key_0) => key_0 in item && isUsable(item[key_0]))) {
2372
+ const updateObject = omit(item, primaryKeysAsStrings);
2373
+ task = supabase.schema(schemaName).from(tableName).update(updateObject);
2374
+ primaryKeys.forEach((key) => {
2375
+ task = task.eq(String(key), item[key]);
2376
+ });
2377
+ } else {
2378
+ task = supabase.schema(schemaName).from(tableName).insert(omit(item, primaryKeysAsStrings));
3003
2379
  }
3004
- } else {
3005
- }
3006
- if (isUsable(item) && (0, import_moment2.default)(item.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
3007
- return item.url;
3008
- }
3009
- const base = supabase.storage.from(entity_2.bucketId);
3010
- let download = options?.download;
3011
- if (typeof options?.download === "string") {
3012
- const ext = entity_2.path.split(".").pop() ?? "";
3013
- download = options?.download.endsWith(ext) ? options?.download : options?.download + "." + ext;
3014
- }
3015
- const newOptions = options ? {
3016
- ...options,
3017
- download
3018
- } : void 0;
3019
- const retryKey = `${entity_2.bucketId}/${entity_2.path}`;
3020
- const currentRetries = retryAttempts.get(retryKey) || 0;
3021
- let url;
3022
- if (isPublic) {
3023
- url = base.getPublicUrl(entity_2.path, newOptions).data.publicUrl;
3024
- } else {
3025
- try {
3026
- console.log("Creating signed URL for", entity_2.path);
3027
- const result = await base.createSignedUrl(entity_2.path, 60 * 100, newOptions);
3028
- url = result.data?.signedUrl;
3029
- if (isUsable(url)) {
3030
- retryAttempts.delete(retryKey);
3031
- } else if (currentRetries < 3) {
3032
- retryAttempts.set(retryKey, currentRetries + 1);
3033
- throw new Error("Failed to get signed URL");
3034
- }
3035
- } catch (error) {
3036
- if (currentRetries < 3) {
3037
- retryAttempts.set(retryKey, currentRetries + 1);
3038
- const delay = Math.min(1e3 * Math.pow(2, currentRetries), 5e3);
3039
- await new Promise((resolve) => setTimeout(resolve, delay));
3040
- return baseFetchUrl(entity_2, options, isPublic);
3041
- }
3042
- retryAttempts.delete(retryKey);
3043
- return void 0;
2380
+ const response = await task.select(query);
2381
+ if (response.error) {
2382
+ throw response.error;
2383
+ }
2384
+ return response.data[0];
2385
+ };
2386
+ $[7] = primaryKeys;
2387
+ $[8] = primaryKeysAsStrings;
2388
+ $[9] = query;
2389
+ $[10] = schemaName;
2390
+ $[11] = supabase;
2391
+ $[12] = tableName;
2392
+ $[13] = t6;
2393
+ } else {
2394
+ t6 = $[13];
2395
+ }
2396
+ const upsertItemAction = t6;
2397
+ let t7;
2398
+ if ($[14] !== upsertItem || $[15] !== upsertItemAction) {
2399
+ t7 = {
2400
+ mutationFn: async (item_0) => {
2401
+ if (Array.isArray(item_0)) {
2402
+ const data = await Promise.all(item_0.map((x) => upsertItemAction(x)));
2403
+ data.filter(_temp2).forEach((x_1) => upsertItem(x_1));
2404
+ return data;
2405
+ }
2406
+ throw new Error("Item must be an array.");
3044
2407
  }
3045
- }
3046
- if (isUsable(url) === false) return url;
3047
- const cachedUrl = {
3048
- key: key_2,
3049
- url,
3050
- expiresOn: (0, import_moment2.default)().add(60 * 100, "seconds").toISOString(true)
3051
2408
  };
3052
- storedUrls.current.set(key_2, cachedUrl);
3053
- db.setItem(key_2, cachedUrl);
3054
- return url;
2409
+ $[14] = upsertItem;
2410
+ $[15] = upsertItemAction;
2411
+ $[16] = t7;
2412
+ } else {
2413
+ t7 = $[16];
3055
2414
  }
3056
- async function fetchUrl(entity_3, options_0) {
3057
- return baseFetchUrl(entity_3, options_0, false);
2415
+ const updateMutation = useMutation2(t7);
2416
+ return updateMutation;
2417
+ }
2418
+ function _temp2(x_0) {
2419
+ return isUsable(x_0);
2420
+ }
2421
+ function _temp3(k) {
2422
+ return String(k);
2423
+ }
2424
+
2425
+ // src/useDbMultiDelete.ts
2426
+ import { c as _c9 } from "react/compiler-runtime";
2427
+ import { useMutation as useMutation3 } from "@tanstack/react-query";
2428
+ function useDbMultiDelete(relation, t0) {
2429
+ const $ = _c9(10);
2430
+ let t1;
2431
+ if ($[0] !== t0) {
2432
+ t1 = t0 === void 0 ? ["id"] : t0;
2433
+ $[0] = t0;
2434
+ $[1] = t1;
2435
+ } else {
2436
+ t1 = $[1];
3058
2437
  }
3059
- async function fetchPublicUrl(entity_4, options_1) {
3060
- return baseFetchUrl(entity_4, options_1, true);
2438
+ const primaryKeys = t1;
2439
+ const tableName = typeof relation === "object" ? relation.table : relation;
2440
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
2441
+ const supabase = useSupabase();
2442
+ let t2;
2443
+ if ($[2] !== primaryKeys) {
2444
+ t2 = primaryKeys.map(_temp4);
2445
+ $[2] = primaryKeys;
2446
+ $[3] = t2;
2447
+ } else {
2448
+ t2 = $[3];
3061
2449
  }
3062
- async function prefetchImage(entity_5, options_2) {
3063
- const url_0 = await fetchUrl(entity_5, options_2);
3064
- if (url_0) {
3065
- new Image().src = url_0;
3066
- }
2450
+ const primaryKeysAsStrings = t2;
2451
+ const t3 = supabase;
2452
+ let t4;
2453
+ if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
2454
+ t4 = t3.schema(schemaName).from(tableName);
2455
+ $[4] = schemaName;
2456
+ $[5] = t3;
2457
+ $[6] = tableName;
2458
+ $[7] = t4;
2459
+ } else {
2460
+ t4 = $[7];
3067
2461
  }
3068
- async function fetchUrls(entities, options_3) {
3069
- const results = /* @__PURE__ */ new Map();
3070
- if (entities.length === 0) return results;
3071
- const optionsString_0 = JSON.stringify(options_3);
3072
- const expirySeconds = 60 * 100;
3073
- const byBucket = /* @__PURE__ */ new Map();
3074
- for (const entity_6 of entities) {
3075
- if (!isUsable(entity_6.bucketId) || !isUsable(entity_6.path)) continue;
3076
- const list = byBucket.get(entity_6.bucketId) ?? [];
3077
- list.push(entity_6);
3078
- byBucket.set(entity_6.bucketId, list);
3079
- }
3080
- for (const [bucketId, bucketEntities] of byBucket) {
3081
- const uncached = [];
3082
- for (const entity_7 of bucketEntities) {
3083
- const key_3 = `${entity_7.bucketId}${entity_7.path}${optionsString_0 ?? ""}-cached-url`;
3084
- const entityKey = `${entity_7.bucketId}/${entity_7.path}`;
3085
- let item_0 = storedUrls.current.get(key_3);
3086
- if (!isUsable(item_0)) {
3087
- item_0 = await db.getItem(key_3) ?? void 0;
3088
- }
3089
- if (isUsable(item_0) && (0, import_moment2.default)(item_0.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
3090
- results.set(entityKey, item_0.url);
2462
+ const deleteManyMutation = useDeleteManyMutation(t4, primaryKeysAsStrings);
2463
+ let t5;
2464
+ if ($[8] !== deleteManyMutation) {
2465
+ t5 = {
2466
+ mutationFn: async (item) => {
2467
+ if (Array.isArray(item)) {
2468
+ const response = await deleteManyMutation.mutateAsync(item);
2469
+ return response;
3091
2470
  } else {
3092
- uncached.push(entity_7);
3093
- }
3094
- }
3095
- if (uncached.length > 0) {
3096
- const paths = uncached.map((e) => e.path);
3097
- const base_0 = supabase.storage.from(bucketId);
3098
- try {
3099
- console.log("Signed URLs created");
3100
- const {
3101
- data,
3102
- error: error_0
3103
- } = await base_0.createSignedUrls(paths, expirySeconds);
3104
- if (!error_0 && data) {
3105
- const expiresOn = (0, import_moment2.default)().add(expirySeconds, "seconds").toISOString(true);
3106
- for (let i = 0; i < uncached.length; i++) {
3107
- const entity_9 = uncached[i];
3108
- const urlData = data[i];
3109
- const entityKey_1 = `${entity_9.bucketId}/${entity_9.path}`;
3110
- const cacheKey = `${entity_9.bucketId}${entity_9.path}${optionsString_0 ?? ""}-cached-url`;
3111
- if (urlData?.signedUrl) {
3112
- results.set(entityKey_1, urlData.signedUrl);
3113
- const cachedUrl_0 = {
3114
- key: cacheKey,
3115
- url: urlData.signedUrl,
3116
- expiresOn
3117
- };
3118
- storedUrls.current.set(cacheKey, cachedUrl_0);
3119
- db.setItem(cacheKey, cachedUrl_0);
3120
- } else {
3121
- results.set(entityKey_1, void 0);
3122
- }
3123
- }
3124
- } else {
3125
- for (const entity_10 of uncached) {
3126
- const entityKey_2 = `${entity_10.bucketId}/${entity_10.path}`;
3127
- const url_2 = await fetchUrl(entity_10, options_3);
3128
- results.set(entityKey_2, url_2);
3129
- }
3130
- }
3131
- } catch {
3132
- for (const entity_8 of uncached) {
3133
- const entityKey_0 = `${entity_8.bucketId}/${entity_8.path}`;
3134
- const url_1 = await fetchUrl(entity_8, options_3);
3135
- results.set(entityKey_0, url_1);
3136
- }
2471
+ throw new Error("Item must be an array.");
3137
2472
  }
3138
2473
  }
3139
- }
3140
- return results;
2474
+ };
2475
+ $[8] = deleteManyMutation;
2476
+ $[9] = t5;
2477
+ } else {
2478
+ t5 = $[9];
2479
+ }
2480
+ const deleteMutation = useMutation3(t5);
2481
+ return deleteMutation;
2482
+ }
2483
+ function _temp4(k) {
2484
+ return String(k);
2485
+ }
2486
+
2487
+ // src/changelog/useChangelogMutations.ts
2488
+ import { c as _c10 } from "react/compiler-runtime";
2489
+ var useUpsertChangelog = () => {
2490
+ const $ = _c10(1);
2491
+ let t0;
2492
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2493
+ t0 = {
2494
+ invalidateTables: ["Changelog", "ChangelogEntry", "ChangelogMedia"]
2495
+ };
2496
+ $[0] = t0;
2497
+ } else {
2498
+ t0 = $[0];
2499
+ }
2500
+ return useDbUpsert("Changelog", t0);
2501
+ };
2502
+ var useDeleteChangelog = () => {
2503
+ return useDbDelete("Changelog");
2504
+ };
2505
+ var useUpsertChangelogEntry = () => {
2506
+ const $ = _c10(1);
2507
+ let t0;
2508
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2509
+ t0 = {
2510
+ invalidateTables: ["ChangelogEntry", "ChangelogMedia"]
2511
+ };
2512
+ $[0] = t0;
2513
+ } else {
2514
+ t0 = $[0];
2515
+ }
2516
+ return useDbUpsert("ChangelogEntry", t0);
2517
+ };
2518
+ var useMultiUpsertChangelogEntries = () => {
2519
+ const $ = _c10(1);
2520
+ let t0;
2521
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2522
+ t0 = ["id"];
2523
+ $[0] = t0;
2524
+ } else {
2525
+ t0 = $[0];
2526
+ }
2527
+ return useDbMultiUpsert("ChangelogEntry", t0, "*, ChangelogMedia (*)");
2528
+ };
2529
+ var useDeleteChangelogEntry = () => {
2530
+ return useDbDelete("ChangelogEntry");
2531
+ };
2532
+ var useMultiDeleteChangelogEntries = () => {
2533
+ return useDbMultiDelete("ChangelogEntry");
2534
+ };
2535
+ var useUpsertChangelogMedia = () => {
2536
+ const $ = _c10(1);
2537
+ let t0;
2538
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
2539
+ t0 = {
2540
+ invalidateTables: ["ChangelogMedia"]
2541
+ };
2542
+ $[0] = t0;
2543
+ } else {
2544
+ t0 = $[0];
3141
2545
  }
2546
+ return useDbUpsert("ChangelogMedia", t0);
2547
+ };
2548
+ var useDeleteChangelogMedia = () => {
2549
+ return useDbDelete("ChangelogMedia");
2550
+ };
2551
+ var useUploadChangelogMedia = () => {
3142
2552
  return {
3143
- fetchUrl,
3144
- fetchUrls,
3145
- prefetchImage,
3146
- fetchPublicUrl,
3147
- expireCache,
3148
- getCacheVersion,
3149
- subscribeToCacheVersion
2553
+ mutateAsync: async () => ({
2554
+ path: "",
2555
+ publicUrl: ""
2556
+ })
3150
2557
  };
3151
- }
2558
+ };
3152
2559
 
3153
- // src/storage/useStoragePath.ts
3154
- import { c as _c15 } from "react/compiler-runtime";
3155
- import { useEffect as useEffect7, useState as useState6 } from "react";
3156
- function getContentType(metadata, path) {
3157
- if (metadata?.contentType) {
3158
- return metadata.contentType;
2560
+ // src/useDbRealtime.ts
2561
+ import { c as _c11 } from "react/compiler-runtime";
2562
+ import { useEffect as useEffect7, useState as useState5, useRef as useRef5 } from "react";
2563
+ import { REALTIME_POSTGRES_CHANGES_LISTEN_EVENT } from "@supabase/supabase-js";
2564
+ import { useDelayedValue } from "@pol-studios/hooks/state";
2565
+ function useDbRealtime(key, query, table, primaryKeys, options) {
2566
+ const $ = _c11(37);
2567
+ const supabase = useSupabase();
2568
+ const tableNameValue = typeof table === "string" ? table : table.table;
2569
+ const schemaValue = typeof table === "string" ? "public" : table.schema;
2570
+ const queriesForTable = useQueriesForTableLoader(tableNameValue);
2571
+ let t0;
2572
+ if ($[0] !== primaryKeys || $[1] !== schemaValue || $[2] !== tableNameValue) {
2573
+ t0 = {
2574
+ primaryKeys,
2575
+ table: tableNameValue,
2576
+ schema: schemaValue
2577
+ };
2578
+ $[0] = primaryKeys;
2579
+ $[1] = schemaValue;
2580
+ $[2] = tableNameValue;
2581
+ $[3] = t0;
2582
+ } else {
2583
+ t0 = $[3];
3159
2584
  }
3160
- const ext = path.split(".").pop()?.toUpperCase();
3161
- return ext || "Unknown";
3162
- }
3163
- function useStoragePath(storagePath, bucketId, t0) {
3164
- const $ = _c15(40);
2585
+ const deleteItem = useDeleteItem(t0);
3165
2586
  let t1;
3166
- if ($[0] !== t0) {
3167
- t1 = t0 === void 0 ? {} : t0;
3168
- $[0] = t0;
3169
- $[1] = t1;
2587
+ if ($[4] !== primaryKeys || $[5] !== schemaValue || $[6] !== tableNameValue) {
2588
+ t1 = {
2589
+ primaryKeys,
2590
+ table: tableNameValue,
2591
+ schema: schemaValue
2592
+ };
2593
+ $[4] = primaryKeys;
2594
+ $[5] = schemaValue;
2595
+ $[6] = tableNameValue;
2596
+ $[7] = t1;
3170
2597
  } else {
3171
- t1 = $[1];
2598
+ t1 = $[7];
3172
2599
  }
3173
- const options = t1;
3174
- const {
3175
- fetchMetadata: t2,
3176
- transform,
3177
- download
3178
- } = options;
3179
- const fetchMetadata = t2 === void 0 ? true : t2;
3180
- const [url, setUrl] = useState6(null);
3181
- const [error, setError] = useState6(null);
3182
- const {
3183
- fetchUrl
3184
- } = useStorageUrl();
3185
- const supabase = useSupabase();
3186
- let t3;
3187
- if ($[2] !== bucketId || $[3] !== download || $[4] !== fetchUrl || $[5] !== storagePath || $[6] !== transform) {
3188
- t3 = () => {
3189
- if (!isUsable(storagePath) || !isUsable(bucketId)) {
3190
- setUrl(null);
2600
+ const upsertItem = useUpsertItem(t1);
2601
+ const [realtimeState, setRealtimeState] = useState5("CLOSED");
2602
+ const [retryTick, setRetryTick] = useState5(0);
2603
+ const channelRef = useRef5(null);
2604
+ const lastRetryTimeRef = useRef5(0);
2605
+ const retryCountRef = useRef5(0);
2606
+ const enabled = options?.enabled ?? true;
2607
+ const filter = options?.filter;
2608
+ const onChange = options?.onChange;
2609
+ const debouncedKey = useDelayedValue(key, 50);
2610
+ let t2;
2611
+ if ($[8] !== deleteItem || $[9] !== enabled || $[10] !== filter || $[11] !== onChange || $[12] !== primaryKeys || $[13] !== queriesForTable || $[14] !== query || $[15] !== retryTick || $[16] !== schemaValue || $[17] !== supabase || $[18] !== tableNameValue || $[19] !== upsertItem) {
2612
+ t2 = () => {
2613
+ if (!enabled) {
2614
+ if (channelRef.current) {
2615
+ channelRef.current.unsubscribe();
2616
+ supabase.removeChannel(channelRef.current);
2617
+ channelRef.current = null;
2618
+ }
2619
+ setRealtimeState("CLOSED");
3191
2620
  return;
3192
2621
  }
3193
- let cancelled = false;
3194
- fetchUrl({
3195
- bucketId,
3196
- path: storagePath
3197
- }, {
3198
- transform,
3199
- download
3200
- }).then((signedUrl) => {
3201
- if (!cancelled) {
3202
- setUrl(signedUrl ?? null);
3203
- setError(null);
2622
+ const now = Date.now();
2623
+ const timeSinceLastRetry = now - lastRetryTimeRef.current;
2624
+ if (timeSinceLastRetry < 2e3 && retryTick > 0) {
2625
+ return;
2626
+ }
2627
+ if (channelRef.current) {
2628
+ channelRef.current.unsubscribe();
2629
+ supabase.removeChannel(channelRef.current);
2630
+ channelRef.current = null;
2631
+ }
2632
+ lastRetryTimeRef.current = now;
2633
+ retryCountRef.current = retryCountRef.current + 1;
2634
+ const channel = supabase.channel(newUuid()).on("postgres_changes", {
2635
+ event: "*",
2636
+ schema: schemaValue,
2637
+ table: tableNameValue,
2638
+ filter
2639
+ }, async (payload) => {
2640
+ let data = payload.new ?? payload.old;
2641
+ if (payload.new && Object.keys(payload.new).length > 0) {
2642
+ const selectQuery = buildNormalizedQuery({
2643
+ queriesForTable,
2644
+ query
2645
+ });
2646
+ if (payload.eventType !== REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE && selectQuery) {
2647
+ if (selectQuery.groupedUserQueryPaths?.every((x) => x.path in data) === false) {
2648
+ const qb = supabase.schema(payload.schema).from(payload.table).select(selectQuery.selectQuery);
2649
+ for (const pk of primaryKeys) {
2650
+ qb.eq(pk.toString(), data[pk]);
2651
+ }
2652
+ const res = await qb.single();
2653
+ if (res.data) {
2654
+ data = normalizeResponse(selectQuery.groupedPaths, res.data);
2655
+ }
2656
+ }
2657
+ }
2658
+ if ("changedBySessionId" in data) {
2659
+ const sessionId = data.changedBySessionId;
2660
+ if (sessionId !== UserSessionId) {
2661
+ await upsertItem(data);
2662
+ }
2663
+ } else {
2664
+ await upsertItem(data);
2665
+ }
3204
2666
  }
3205
- }).catch((err) => {
3206
- if (!cancelled) {
3207
- setError(err instanceof Error ? err : new Error(String(err)));
3208
- setUrl(null);
2667
+ if (payload.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
2668
+ await deleteItem(payload.old);
2669
+ }
2670
+ if (payload.errors?.length > 0) {
2671
+ setRealtimeState("CHANNEL_ERROR");
2672
+ }
2673
+ if (onChange) {
2674
+ onChange(payload);
2675
+ }
2676
+ }).on("postgres_changes", {
2677
+ event: "DELETE",
2678
+ schema: schemaValue,
2679
+ table: tableNameValue
2680
+ }, async (payload_0) => {
2681
+ if (payload_0.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
2682
+ await deleteItem(payload_0.old);
2683
+ }
2684
+ }).subscribe((status) => {
2685
+ setRealtimeState(status);
2686
+ if (status === "SUBSCRIBED") {
2687
+ retryCountRef.current = 0;
3209
2688
  }
3210
2689
  });
2690
+ channelRef.current = channel;
3211
2691
  return () => {
3212
- cancelled = true;
2692
+ if (channelRef.current) {
2693
+ channelRef.current.unsubscribe();
2694
+ supabase.removeChannel(channelRef.current);
2695
+ channelRef.current = null;
2696
+ }
3213
2697
  };
3214
2698
  };
3215
- $[2] = bucketId;
3216
- $[3] = download;
3217
- $[4] = fetchUrl;
3218
- $[5] = storagePath;
3219
- $[6] = transform;
3220
- $[7] = t3;
3221
- } else {
3222
- t3 = $[7];
3223
- }
3224
- let t4;
3225
- if ($[8] !== transform) {
3226
- t4 = JSON.stringify(transform);
3227
- $[8] = transform;
3228
- $[9] = t4;
3229
- } else {
3230
- t4 = $[9];
3231
- }
3232
- let t5;
3233
- if ($[10] !== bucketId || $[11] !== download || $[12] !== storagePath || $[13] !== t4) {
3234
- t5 = [storagePath, bucketId, t4, download];
3235
- $[10] = bucketId;
3236
- $[11] = download;
3237
- $[12] = storagePath;
3238
- $[13] = t4;
3239
- $[14] = t5;
3240
- } else {
3241
- t5 = $[14];
3242
- }
3243
- useEffect7(t3, t5);
3244
- let t6;
3245
- if ($[15] !== bucketId || $[16] !== storagePath || $[17] !== supabase) {
3246
- t6 = supabase.schema("storage").from("objects").select("metadata").eq("bucket_id", bucketId).eq("name", storagePath ?? "").maybeSingle();
3247
- $[15] = bucketId;
3248
- $[16] = storagePath;
2699
+ $[8] = deleteItem;
2700
+ $[9] = enabled;
2701
+ $[10] = filter;
2702
+ $[11] = onChange;
2703
+ $[12] = primaryKeys;
2704
+ $[13] = queriesForTable;
2705
+ $[14] = query;
2706
+ $[15] = retryTick;
2707
+ $[16] = schemaValue;
3249
2708
  $[17] = supabase;
3250
- $[18] = t6;
3251
- } else {
3252
- t6 = $[18];
3253
- }
3254
- const storageQuery = t6;
3255
- let t7;
3256
- if ($[19] !== bucketId || $[20] !== fetchMetadata || $[21] !== storagePath) {
3257
- t7 = fetchMetadata && isUsable(storagePath) && isUsable(bucketId);
3258
- $[19] = bucketId;
3259
- $[20] = fetchMetadata;
3260
- $[21] = storagePath;
3261
- $[22] = t7;
3262
- } else {
3263
- t7 = $[22];
3264
- }
3265
- let t8;
3266
- if ($[23] !== t7) {
3267
- t8 = {
3268
- enabled: t7
3269
- };
3270
- $[23] = t7;
3271
- $[24] = t8;
2709
+ $[18] = tableNameValue;
2710
+ $[19] = upsertItem;
2711
+ $[20] = t2;
3272
2712
  } else {
3273
- t8 = $[24];
2713
+ t2 = $[20];
3274
2714
  }
3275
- const metadataRequest = useDbQuery(storageQuery, t8);
3276
- const metadata = metadataRequest.data?.metadata ?? null;
3277
- const t9 = storagePath ?? "";
3278
- let t10;
3279
- if ($[25] !== metadata || $[26] !== t9) {
3280
- t10 = getContentType(metadata, t9);
3281
- $[25] = metadata;
3282
- $[26] = t9;
3283
- $[27] = t10;
2715
+ let t3;
2716
+ if ($[21] !== primaryKeys) {
2717
+ t3 = primaryKeys.join(",");
2718
+ $[21] = primaryKeys;
2719
+ $[22] = t3;
3284
2720
  } else {
3285
- t10 = $[27];
2721
+ t3 = $[22];
3286
2722
  }
3287
- const contentType = t10;
3288
- let t11;
3289
- if ($[28] !== error || $[29] !== fetchMetadata || $[30] !== metadataRequest.isFetching || $[31] !== storagePath || $[32] !== url) {
3290
- t11 = isUsable(storagePath) && url === null && error === null || fetchMetadata && metadataRequest.isFetching;
3291
- $[28] = error;
3292
- $[29] = fetchMetadata;
3293
- $[30] = metadataRequest.isFetching;
3294
- $[31] = storagePath;
3295
- $[32] = url;
3296
- $[33] = t11;
2723
+ let t4;
2724
+ if ($[23] !== debouncedKey || $[24] !== enabled || $[25] !== filter || $[26] !== query || $[27] !== retryTick || $[28] !== schemaValue || $[29] !== supabase || $[30] !== t3 || $[31] !== tableNameValue) {
2725
+ t4 = [supabase, tableNameValue, schemaValue, enabled, filter, query, t3, retryTick, debouncedKey];
2726
+ $[23] = debouncedKey;
2727
+ $[24] = enabled;
2728
+ $[25] = filter;
2729
+ $[26] = query;
2730
+ $[27] = retryTick;
2731
+ $[28] = schemaValue;
2732
+ $[29] = supabase;
2733
+ $[30] = t3;
2734
+ $[31] = tableNameValue;
2735
+ $[32] = t4;
3297
2736
  } else {
3298
- t11 = $[33];
2737
+ t4 = $[32];
3299
2738
  }
3300
- const isLoading = t11;
3301
- let t12;
3302
- if ($[34] !== contentType || $[35] !== error || $[36] !== isLoading || $[37] !== metadata || $[38] !== url) {
3303
- t12 = {
3304
- url,
3305
- metadata,
3306
- contentType,
3307
- isLoading,
3308
- error
2739
+ useEffect7(t2, t4);
2740
+ let t5;
2741
+ let t6;
2742
+ if ($[33] !== enabled || $[34] !== realtimeState) {
2743
+ t5 = () => {
2744
+ if (!enabled || realtimeState === "SUBSCRIBED") {
2745
+ retryCountRef.current = 0;
2746
+ return;
2747
+ }
2748
+ const delay = Math.min(5e3 * Math.pow(2, retryCountRef.current), 6e4);
2749
+ const id = setTimeout(() => {
2750
+ setRetryTick(_temp5);
2751
+ }, delay);
2752
+ return () => clearTimeout(id);
3309
2753
  };
3310
- $[34] = contentType;
3311
- $[35] = error;
3312
- $[36] = isLoading;
3313
- $[37] = metadata;
3314
- $[38] = url;
3315
- $[39] = t12;
2754
+ t6 = [realtimeState, enabled];
2755
+ $[33] = enabled;
2756
+ $[34] = realtimeState;
2757
+ $[35] = t5;
2758
+ $[36] = t6;
3316
2759
  } else {
3317
- t12 = $[39];
2760
+ t5 = $[35];
2761
+ t6 = $[36];
3318
2762
  }
3319
- return t12;
2763
+ useEffect7(t5, t6);
2764
+ return realtimeState;
2765
+ }
2766
+ function _temp5(t) {
2767
+ return t + 1;
3320
2768
  }
3321
2769
 
3322
- // src/storage/bucketConfig.ts
3323
- var BUCKETS = {
3324
- AVATARS: "avatars",
3325
- FIXTURE_CATALOG_COVER: "fixture-catalog-cover",
3326
- FIXTURE_ATTACHMENTS: "fixture-attachments",
3327
- UNIT_DOCUMENTATION: "unit-documentation-attachments",
3328
- DATASHEETS: "datasheets",
3329
- PATTERNS: "patterns",
3330
- LOGOS: "logos",
3331
- RECEIPTS: "receipts",
3332
- TICKET_ATTACHMENTS: "ticket-attachment",
3333
- PROCESS_RESULTS: "process-results",
3334
- DATA_EXCHANGE_IMPORTS: "data-exchange-imports",
3335
- EMAIL_TEMPLATES: "email-templates",
3336
- EMAIL_TEMPLATES_ASSETS: "email-templates-assets"
3337
- };
3338
-
3339
- // src/utilities/query-utils.ts
3340
- function createInCondition(column, values) {
3341
- let condition = "";
3342
- if (values.length > 2e3) {
3343
- throw new Error("Too many values to create in condition");
3344
- }
3345
- chunkArray(values, 99).forEach((x, index) => {
3346
- if (index == 0) {
3347
- condition = `${column}.in.(${x.join(",")})`;
3348
- return;
2770
+ // src/useDbRealtimeQuery.tsx
2771
+ import { c as _c12 } from "react/compiler-runtime";
2772
+ function convertFilterToRealtimeQuery(filters) {
2773
+ function convert(filter) {
2774
+ if (!filter) return "";
2775
+ if ("path" in filter) {
2776
+ if (filter.path.includes(".")) return "";
2777
+ let valueString = filter.value?.toString() ?? "null";
2778
+ if (filter.operator === "in") {
2779
+ valueString = '("' + valueString.slice(2, valueString.length - 2).split(",").join('","') + '")';
2780
+ }
2781
+ return `${filter.path}=${filter.negate ? "not." : ""}${filter.operator}.${valueString}`;
2782
+ } else {
2783
+ if (filter.or) {
2784
+ return `(${filter.or.map((f) => convert(f)).join("|")})`;
2785
+ } else if (filter.and) {
2786
+ return `(${filter.and.map((f) => convert(f)).join("&")})`;
2787
+ }
3349
2788
  }
3350
- condition += `,${column}.in.(${x.join(",")})`;
3351
- });
3352
- return condition;
2789
+ return "";
2790
+ }
2791
+ return convert(filters[0]);
3353
2792
  }
3354
-
3355
- // src/changelog/useChangelogMutations.ts
3356
- import { c as _c16 } from "react/compiler-runtime";
3357
- var useUpsertChangelog = () => {
3358
- const $ = _c16(1);
3359
- let t0;
3360
- if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3361
- t0 = {
3362
- invalidateTables: ["Changelog", "ChangelogEntry", "ChangelogMedia"]
3363
- };
2793
+ function useDbRealtimeQuery(query, config, t0) {
2794
+ const $ = _c12(27);
2795
+ let t1;
2796
+ if ($[0] !== t0) {
2797
+ t1 = t0 === void 0 ? ["id"] : t0;
3364
2798
  $[0] = t0;
2799
+ $[1] = t1;
3365
2800
  } else {
3366
- t0 = $[0];
2801
+ t1 = $[1];
3367
2802
  }
3368
- return useDbUpsert("Changelog", t0);
3369
- };
3370
- var useDeleteChangelog = () => {
3371
- return useDbDelete("Changelog");
3372
- };
3373
- var useUpsertChangelogEntry = () => {
3374
- const $ = _c16(1);
3375
- let t0;
3376
- if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3377
- t0 = {
3378
- invalidateTables: ["ChangelogEntry", "ChangelogMedia"]
2803
+ const primaryKeys = t1;
2804
+ const t2 = query;
2805
+ let t3;
2806
+ if ($[2] !== t2) {
2807
+ t3 = new PostgrestParser(t2);
2808
+ $[2] = t2;
2809
+ $[3] = t3;
2810
+ } else {
2811
+ t3 = $[3];
2812
+ }
2813
+ const parser = t3;
2814
+ const request = useQuery(query, config);
2815
+ let filter;
2816
+ let selectStatement;
2817
+ let t4;
2818
+ let t5;
2819
+ if ($[4] !== parser.filters || $[5] !== parser.select || $[6] !== query || $[7] !== request.data) {
2820
+ const queryKey = encode(query, false);
2821
+ let t62;
2822
+ if ($[12] !== parser.filters || $[13] !== request.data) {
2823
+ const filterString = convertFilterToRealtimeQuery(parser.filters);
2824
+ filter = request.data && typeof request.data === "object" && "id" in request.data ? "id=eq." + request.data.id : filterString;
2825
+ if (filter.includes('in.(\\"\\")')) {
2826
+ filter = void 0;
2827
+ }
2828
+ t62 = isNullOrWhitespace(filter);
2829
+ $[12] = parser.filters;
2830
+ $[13] = request.data;
2831
+ $[14] = filter;
2832
+ $[15] = t62;
2833
+ } else {
2834
+ filter = $[14];
2835
+ t62 = $[15];
2836
+ }
2837
+ if (t62) {
2838
+ filter = void 0;
2839
+ }
2840
+ selectStatement = parser.select;
2841
+ t4 = useDbRealtime;
2842
+ t5 = queryKey.join("-");
2843
+ $[4] = parser.filters;
2844
+ $[5] = parser.select;
2845
+ $[6] = query;
2846
+ $[7] = request.data;
2847
+ $[8] = filter;
2848
+ $[9] = selectStatement;
2849
+ $[10] = t4;
2850
+ $[11] = t5;
2851
+ } else {
2852
+ filter = $[8];
2853
+ selectStatement = $[9];
2854
+ t4 = $[10];
2855
+ t5 = $[11];
2856
+ }
2857
+ let t6;
2858
+ if ($[16] !== parser.schema || $[17] !== parser.table) {
2859
+ t6 = {
2860
+ schema: parser.schema,
2861
+ table: parser.table
3379
2862
  };
3380
- $[0] = t0;
2863
+ $[16] = parser.schema;
2864
+ $[17] = parser.table;
2865
+ $[18] = t6;
3381
2866
  } else {
3382
- t0 = $[0];
2867
+ t6 = $[18];
3383
2868
  }
3384
- return useDbUpsert("ChangelogEntry", t0);
3385
- };
3386
- var useMultiUpsertChangelogEntries = () => {
3387
- const $ = _c16(1);
3388
- let t0;
3389
- if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3390
- t0 = ["id"];
3391
- $[0] = t0;
2869
+ const t7 = typeof config?.enabled === "boolean" ? config.enabled : true;
2870
+ let t8;
2871
+ if ($[19] !== filter || $[20] !== t7) {
2872
+ t8 = {
2873
+ filter,
2874
+ enabled: t7
2875
+ };
2876
+ $[19] = filter;
2877
+ $[20] = t7;
2878
+ $[21] = t8;
3392
2879
  } else {
3393
- t0 = $[0];
2880
+ t8 = $[21];
3394
2881
  }
3395
- return useDbMultiUpsert("ChangelogEntry", t0, "*, ChangelogMedia (*)");
3396
- };
3397
- var useDeleteChangelogEntry = () => {
3398
- return useDbDelete("ChangelogEntry");
3399
- };
3400
- var useMultiDeleteChangelogEntries = () => {
3401
- return useDbMultiDelete("ChangelogEntry");
3402
- };
3403
- var useUpsertChangelogMedia = () => {
3404
- const $ = _c16(1);
3405
- let t0;
3406
- if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3407
- t0 = {
3408
- invalidateTables: ["ChangelogMedia"]
2882
+ const realtimeStatus = t4(t5, selectStatement, t6, primaryKeys, t8);
2883
+ const outputRealtimeStatus = request.isFetching ? "Loading..." : realtimeStatus;
2884
+ const t9 = request.data;
2885
+ const t10 = realtimeStatus == "SUBSCRIBED";
2886
+ let t11;
2887
+ if ($[22] !== outputRealtimeStatus || $[23] !== request || $[24] !== t10 || $[25] !== t9) {
2888
+ t11 = {
2889
+ ...request,
2890
+ data: t9,
2891
+ realtimeStatus: outputRealtimeStatus,
2892
+ isRealtimeConnected: t10,
2893
+ isRealtimeLoading: request.isFetching
3409
2894
  };
3410
- $[0] = t0;
2895
+ $[22] = outputRealtimeStatus;
2896
+ $[23] = request;
2897
+ $[24] = t10;
2898
+ $[25] = t9;
2899
+ $[26] = t11;
3411
2900
  } else {
3412
- t0 = $[0];
2901
+ t11 = $[26];
3413
2902
  }
3414
- return useDbUpsert("ChangelogMedia", t0);
3415
- };
3416
- var useDeleteChangelogMedia = () => {
3417
- return useDbDelete("ChangelogMedia");
3418
- };
3419
- var useUploadChangelogMedia = () => {
3420
- return {
3421
- mutateAsync: async () => ({
3422
- path: "",
3423
- publicUrl: ""
3424
- })
3425
- };
3426
- };
2903
+ return t11;
2904
+ }
3427
2905
 
3428
2906
  // src/changelog/useChangelogQuery.ts
3429
- import { c as _c17 } from "react/compiler-runtime";
2907
+ import { c as _c13 } from "react/compiler-runtime";
3430
2908
  var useChangelogs = (options) => {
3431
2909
  const supabase = useSupabase();
3432
2910
  const query = supabase.from("Changelog").select(`
@@ -3480,7 +2958,7 @@ var usePublishedChangelogs = (options) => {
3480
2958
  });
3481
2959
  };
3482
2960
  var useChangelogById = (id) => {
3483
- const $ = _c17(5);
2961
+ const $ = _c13(5);
3484
2962
  const supabase = useSupabase();
3485
2963
  let t0;
3486
2964
  if ($[0] !== id || $[1] !== supabase) {
@@ -3512,7 +2990,7 @@ var useChangelogById = (id) => {
3512
2990
  return useDbQuery(t0, t2);
3513
2991
  };
3514
2992
  var useChangelogBySlug = (slug) => {
3515
- const $ = _c17(5);
2993
+ const $ = _c13(5);
3516
2994
  const supabase = useSupabase();
3517
2995
  let t0;
3518
2996
  if ($[0] !== slug || $[1] !== supabase) {
@@ -3544,7 +3022,7 @@ var useChangelogBySlug = (slug) => {
3544
3022
  return useDbQuery(t0, t2);
3545
3023
  };
3546
3024
  var useChangelogEntries = (changelogId) => {
3547
- const $ = _c17(5);
3025
+ const $ = _c13(5);
3548
3026
  const supabase = useSupabase();
3549
3027
  let t0;
3550
3028
  if ($[0] !== changelogId || $[1] !== supabase) {
@@ -3575,7 +3053,7 @@ var useChangelogEntries = (changelogId) => {
3575
3053
  return useDbQuery(t0, t2);
3576
3054
  };
3577
3055
  var useChangelogMedia = (entryId) => {
3578
- const $ = _c17(5);
3056
+ const $ = _c13(5);
3579
3057
  const supabase = useSupabase();
3580
3058
  let t0;
3581
3059
  if ($[0] !== entryId || $[1] !== supabase) {
@@ -3604,10 +3082,10 @@ var useChangelogMedia = (entryId) => {
3604
3082
  };
3605
3083
 
3606
3084
  // src/nl-training/useFeedbackList.ts
3607
- import { c as _c18 } from "react/compiler-runtime";
3085
+ import { c as _c14 } from "react/compiler-runtime";
3608
3086
  import { useQuery as useQuery2 } from "@tanstack/react-query";
3609
3087
  function useFeedbackList(t0) {
3610
- const $ = _c18(10);
3088
+ const $ = _c14(10);
3611
3089
  let t1;
3612
3090
  if ($[0] !== t0) {
3613
3091
  t1 = t0 === void 0 ? {} : t0;
@@ -3688,10 +3166,10 @@ function useFeedbackList(t0) {
3688
3166
  }
3689
3167
 
3690
3168
  // src/nl-training/useSubmitFeedback.ts
3691
- import { c as _c19 } from "react/compiler-runtime";
3692
- import { useMutation as useMutation6, useQueryClient } from "@tanstack/react-query";
3169
+ import { c as _c15 } from "react/compiler-runtime";
3170
+ import { useMutation as useMutation4, useQueryClient } from "@tanstack/react-query";
3693
3171
  function useSubmitFeedback() {
3694
- const $ = _c19(7);
3172
+ const $ = _c15(7);
3695
3173
  const supabase = useSupabase();
3696
3174
  const queryClient = useQueryClient();
3697
3175
  let t0;
@@ -3741,14 +3219,14 @@ function useSubmitFeedback() {
3741
3219
  } else {
3742
3220
  t2 = $[6];
3743
3221
  }
3744
- return useMutation6(t2);
3222
+ return useMutation4(t2);
3745
3223
  }
3746
3224
 
3747
3225
  // src/nl-training/useApplyFeedback.ts
3748
- import { c as _c20 } from "react/compiler-runtime";
3749
- import { useMutation as useMutation7, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
3226
+ import { c as _c16 } from "react/compiler-runtime";
3227
+ import { useMutation as useMutation5, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
3750
3228
  function useApplyFeedback() {
3751
- const $ = _c20(7);
3229
+ const $ = _c16(7);
3752
3230
  const supabase = useSupabase();
3753
3231
  const queryClient = useQueryClient2();
3754
3232
  let t0;
@@ -3798,14 +3276,14 @@ function useApplyFeedback() {
3798
3276
  } else {
3799
3277
  t2 = $[6];
3800
3278
  }
3801
- return useMutation7(t2);
3279
+ return useMutation5(t2);
3802
3280
  }
3803
3281
 
3804
3282
  // src/nl-training/useResolveFeedback.ts
3805
- import { c as _c21 } from "react/compiler-runtime";
3806
- import { useMutation as useMutation8, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
3283
+ import { c as _c17 } from "react/compiler-runtime";
3284
+ import { useMutation as useMutation6, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
3807
3285
  function useResolveFeedback() {
3808
- const $ = _c21(7);
3286
+ const $ = _c17(7);
3809
3287
  const supabase = useSupabase();
3810
3288
  const queryClient = useQueryClient3();
3811
3289
  let t0;
@@ -3855,21 +3333,10 @@ function useResolveFeedback() {
3855
3333
  } else {
3856
3334
  t2 = $[6];
3857
3335
  }
3858
- return useMutation8(t2);
3336
+ return useMutation6(t2);
3859
3337
  }
3860
3338
 
3861
3339
  export {
3862
- useDbDelete,
3863
- useDbInfiniteQuery,
3864
- useDbInsert,
3865
- useDbMultiDelete,
3866
- useDbMultiUpsert,
3867
- useDbPartialAdvanceQuery,
3868
- useDbPartialQuery,
3869
- useDbRealtime,
3870
- convertFilterToRealtimeQuery,
3871
- useDbRealtimeQuery,
3872
- useDbUpdate,
3873
3340
  useMutationSuccess,
3874
3341
  useMutationSuccessRN,
3875
3342
  ADAPTER_STRATEGIES,
@@ -3895,6 +3362,9 @@ export {
3895
3362
  useStoragePath,
3896
3363
  BUCKETS,
3897
3364
  createInCondition,
3365
+ useDbDelete,
3366
+ useDbMultiUpsert,
3367
+ useDbMultiDelete,
3898
3368
  useUpsertChangelog,
3899
3369
  useDeleteChangelog,
3900
3370
  useUpsertChangelogEntry,
@@ -3904,6 +3374,9 @@ export {
3904
3374
  useUpsertChangelogMedia,
3905
3375
  useDeleteChangelogMedia,
3906
3376
  useUploadChangelogMedia,
3377
+ useDbRealtime,
3378
+ convertFilterToRealtimeQuery,
3379
+ useDbRealtimeQuery,
3907
3380
  useChangelogs,
3908
3381
  usePublishedChangelogs,
3909
3382
  useChangelogById,
@@ -3915,4 +3388,4 @@ export {
3915
3388
  useApplyFeedback,
3916
3389
  useResolveFeedback
3917
3390
  };
3918
- //# sourceMappingURL=chunk-R5B2XMN5.js.map
3391
+ //# sourceMappingURL=chunk-I4BDZDHX.js.map