@aiao/rxdb-adapter-supabase 0.0.20 → 0.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.
package/dist/index.js CHANGED
@@ -19,18 +19,47 @@ var p = class extends Error {
19
19
  constructor(e) {
20
20
  super(e, "DATA_ERROR"), this.name = "SupabaseDataError";
21
21
  }
22
- }, _ = {
22
+ }, _ = "rxdb", v = "public", y = (e) => e && (e === _ ? v : e);
23
+ //#endregion
24
+ //#region src/entity_scope.ts
25
+ function b(e) {
26
+ let t = /* @__PURE__ */ new Map();
27
+ for (let n of e.config.entities) {
28
+ let e = o(n), r = e.namespace || "public", i = {
29
+ namespace: r,
30
+ entity: e.name,
31
+ schema: y(r) ?? "public",
32
+ tableName: e.tableName
33
+ };
34
+ t.set(`${i.namespace}:${i.entity}`, i);
35
+ }
36
+ return [...t.values()];
37
+ }
38
+ function x(e, t) {
39
+ let n = b(e), r = t.indexOf(":"), i = r > 0 ? n.filter((e) => e.namespace === t.slice(0, r) && e.entity === t.slice(r + 1)) : n.filter((e) => e.entity === t);
40
+ if (i.length === 1) return i[0];
41
+ throw i.length > 1 ? new m(`Entity "${t}" is configured in multiple namespaces`) : new m(`Entity "${t}" is not configured`);
42
+ }
43
+ function S(e, t, n) {
44
+ let r = t || "public";
45
+ return b(e).some((e) => e.namespace === r && e.entity === n);
46
+ }
47
+ //#endregion
48
+ //#region src/handle_supabase_change.ts
49
+ var C = {
23
50
  INSERT: e,
24
51
  UPDATE: n,
25
52
  DELETE: t
26
53
  };
27
- function v(e, t) {
54
+ function w(e, t) {
28
55
  if (t.table !== "rxdb_change" || t.eventType !== "INSERT") return;
29
56
  let n = t.new;
30
57
  if (!n) return;
31
- let { namespace: r, entity: i, entityId: a, type: o, branchId: s, patch: c, clientId: l } = n, u = e.rxdb.context.clientId;
58
+ let { namespace: r, entity: i, entityId: a, type: o, branchId: s, patch: c, clientId: l } = n;
59
+ if (!i || !S(e.rxdb, r, i)) return;
60
+ let u = e.rxdb.context.clientId;
32
61
  if (l && u && l === u || !a || !o) return;
33
- let d = o, f = _[d];
62
+ let d = o, f = C[d];
34
63
  if (!f) return;
35
64
  let p = {
36
65
  id: a,
@@ -48,7 +77,7 @@ function v(e, t) {
48
77
  }
49
78
  //#endregion
50
79
  //#region src/rule_group_builder.ts
51
- var y = {
80
+ var T = {
52
81
  "=": "eq",
53
82
  "!=": "neq",
54
83
  "<": "lt",
@@ -61,37 +90,41 @@ var y = {
61
90
  startsWith: "ilike",
62
91
  endsWith: "ilike"
63
92
  };
64
- function b(e) {
65
- return e instanceof Date ? e.toISOString() : Array.isArray(e) ? e.map(b) : e;
93
+ function E(e) {
94
+ return e instanceof Date ? e.toISOString() : Array.isArray(e) ? e.map(E) : e;
66
95
  }
67
- function x(e, t) {
68
- let n = b(e);
96
+ function D(e) {
97
+ let t = String(e);
98
+ return /[,()"\\]/.test(t) ? `"${t.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"` : t;
99
+ }
100
+ function O(e, t) {
101
+ let n = E(e);
69
102
  if (!Array.isArray(n) || n.length !== 2) throw Error(`${t} operator requires a two-item array`);
70
103
  return [n[0], n[1]];
71
104
  }
72
- function S(e, t, n) {
105
+ function k(e, t, n) {
73
106
  return !t || !e.mappedEntity ? n : t.getEntityMetadata(e.mappedEntity, e.mappedNamespace ?? "") ?? n;
74
107
  }
75
- function C(e, t) {
76
- let n = b(t);
108
+ function A(e, t) {
109
+ let n = E(t);
77
110
  switch (e) {
78
111
  case "=":
79
112
  case "!=":
80
113
  case "<":
81
114
  case "<=":
82
115
  case ">":
83
- case ">=": return `${y[e]}.${n}`;
116
+ case ">=": return `${T[e]}.${D(n)}`;
84
117
  case "in":
85
118
  if (!Array.isArray(n)) throw Error("IN operator requires array");
86
- return `in.(${n.join(",")})`;
119
+ return `in.(${n.map(D).join(",")})`;
87
120
  case "contains":
88
- case "includes": return `ilike.*${n}*`;
89
- case "startsWith": return `ilike.${n}*`;
90
- case "endsWith": return `ilike.*${n}`;
121
+ case "includes": return `ilike.${D(`*${n}*`)}`;
122
+ case "startsWith": return `ilike.${D(`${n}*`)}`;
123
+ case "endsWith": return `ilike.${D(`*${n}`)}`;
91
124
  default: throw Error(`Unsupported operator: ${e}`);
92
125
  }
93
126
  }
94
- function w(e, t, n) {
127
+ function j(e, t, n) {
95
128
  let [r, ...i] = e.split(".");
96
129
  return i.length === 0 ? {
97
130
  field: e,
@@ -102,51 +135,52 @@ function w(e, t, n) {
102
135
  operator: "exists",
103
136
  where: {
104
137
  combinator: "and",
105
- rules: [w(i.join("."), t, n)]
138
+ rules: [j(i.join("."), t, n)]
106
139
  }
107
140
  };
108
141
  }
109
- function T(e, t, n, r) {
142
+ function M(e, t, n, r) {
143
+ let i = e;
110
144
  if (!t?.rules?.length) return e;
111
145
  if (t.rules.length === 1) {
112
- let i = t.rules[0];
113
- return s(i) ? T(e, i, n, r) : E(e, i, n, r);
146
+ let e = t.rules[0];
147
+ return s(e) ? M(i, e, n, r) : N(i, e, n, r);
114
148
  }
115
- if (t.combinator === "and") return t.rules.reduce((e, t) => s(t) ? T(e, t, n, r) : E(e, t, n, r), e);
116
- let i = t.rules.map((e) => {
149
+ if (t.combinator === "and") return t.rules.reduce((e, t) => s(t) ? M(e, t, n, r) : N(e, t, n, r), i);
150
+ let a = t.rules.map((e) => {
117
151
  if (s(e)) throw Error("Nested OR conditions not supported");
118
152
  let { field: t, operator: n, value: r } = e;
119
- return `${t}.${C(n, r)}`;
153
+ return `${t}.${A(n, r)}`;
120
154
  });
121
- return e.or(i.join(","));
155
+ return i.or(a.join(","));
122
156
  }
123
- function E(e, t, n, r) {
157
+ function N(e, t, n, r) {
124
158
  let { field: i, operator: a, value: o } = t;
125
- return typeof i == "string" && i.includes(".") ? E(e, w(i, a, o), n, r) : a === "exists" || a === "notExists" ? D(e, t, n, r) : k(e, i, a, o);
159
+ return typeof i == "string" && i.includes(".") ? N(e, j(i, a, o), n, r) : a === "exists" || a === "notExists" ? P(e, t, n, r) : I(e, i, a, o);
126
160
  }
127
- function D(e, t, n, r) {
161
+ function P(e, t, n, r) {
128
162
  let { field: i, operator: a, where: o } = t, s = String(i), c = n?.relationMap?.get(s);
129
163
  if (!c) throw Error(`Relation '${s}' not found in '${n?.name || "unknown"}'`);
130
- let l = n ? S(c, r, n) : void 0;
164
+ let l = n ? k(c, r, n) : void 0;
131
165
  if (!l) throw Error(`Cannot resolve metadata for '${s}'`);
132
- return o?.rules?.length ? O(a === "exists" ? e.not(s, "is", null) : e, s, o, l, r, s) : a === "exists" ? e.not(s, "is", null) : e.is(s, null);
166
+ return o?.rules?.length ? F(a === "exists" ? e.not(s, "is", null) : e, s, o, l, r, s) : a === "exists" ? e.not(s, "is", null) : e.is(s, null);
133
167
  }
134
- function O(e, t, n, r, i, a = "") {
168
+ function F(e, t, n, r, i, a = "") {
135
169
  if (!n?.rules?.length) return e;
136
170
  let o = e;
137
171
  for (let e of n.rules) {
138
172
  if (s(e)) {
139
- o = O(o, t, e, r, i, a);
173
+ o = F(o, t, e, r, i, a);
140
174
  continue;
141
175
  }
142
176
  let { field: n, operator: c, value: l, where: u } = e;
143
177
  if (c === "exists" || c === "notExists") {
144
178
  let e = r?.relationMap?.get(String(n));
145
179
  if (!e) throw Error(`Relation '${n}' not found in ${r.name}`);
146
- let t = S(e, i, r), s = String(n), l = u;
180
+ let t = k(e, i, r), s = String(n), l = u;
147
181
  if (l?.rules?.length) {
148
182
  let e = a ? `${a}.${s}` : s;
149
- o = O(c === "exists" ? o.not(e, "is", null) : o, s, l, t, i, e);
183
+ o = F(c === "exists" ? o.not(e, "is", null) : o, s, l, t, i, e);
150
184
  } else {
151
185
  let e = a ? `${a}.${s}` : s;
152
186
  o = c === "exists" ? o.not(e, "is", null) : o.is(e, null);
@@ -154,14 +188,14 @@ function O(e, t, n, r, i, a = "") {
154
188
  continue;
155
189
  }
156
190
  let d = a ? `${a}.${n}` : `${t}.${n}`;
157
- o = k(o, d, c, l);
191
+ o = I(o, d, c, l);
158
192
  }
159
193
  return o;
160
194
  }
161
- function k(e, t, n, r) {
162
- let i = b(r);
195
+ function I(e, t, n, r) {
196
+ let i = E(r);
163
197
  if (t.includes(".") && n === "between") {
164
- let [n, i] = x(r, "between");
198
+ let [n, i] = O(r, "between");
165
199
  return e.gte(t, n).lte(t, i);
166
200
  }
167
201
  switch (n) {
@@ -172,7 +206,7 @@ function k(e, t, n, r) {
172
206
  case "<=": return e.lte(t, i);
173
207
  case ">=": return e.gte(t, i);
174
208
  case "in": return e.in(t, i);
175
- case "notIn": return e.not(t, "in", `(${i.join(",")})`);
209
+ case "notIn": return e.not(t, "in", `(${i.map(D).join(",")})`);
176
210
  case "contains":
177
211
  case "includes": return e.ilike(t, `%${i}%`);
178
212
  case "notContains": return e.not(t, "ilike", `%${i}%`);
@@ -181,12 +215,12 @@ function k(e, t, n, r) {
181
215
  case "endsWith": return e.ilike(t, `%${i}`);
182
216
  case "notEndsWith": return e.not(t, "ilike", `%${i}`);
183
217
  case "between": {
184
- let [n, i] = x(r, "between");
218
+ let [n, i] = O(r, "between");
185
219
  return e.gte(t, n).lte(t, i);
186
220
  }
187
221
  case "notBetween": {
188
- let [n, i] = x(r, "notBetween");
189
- return e.or(`${t}.lt.${n},${t}.gt.${i}`);
222
+ let [n, i] = O(r, "notBetween");
223
+ return e.or(`${t}.lt.${D(n)},${t}.gt.${D(i)}`);
190
224
  }
191
225
  case "null":
192
226
  case "isNull": return e.is(t, null);
@@ -197,7 +231,7 @@ function k(e, t, n, r) {
197
231
  }
198
232
  //#endregion
199
233
  //#region src/RxDBAdapterSupabase.utils.ts
200
- function A(e) {
234
+ function L(e) {
201
235
  let t = /* @__PURE__ */ new Map();
202
236
  for (let n of e) {
203
237
  let e = n.constructor;
@@ -205,7 +239,7 @@ function A(e) {
205
239
  }
206
240
  return t;
207
241
  }
208
- function j(e, t) {
242
+ function R(e, t) {
209
243
  let n = [];
210
244
  for (let [r, i] of e) {
211
245
  let e = o(r), a = Array.from(i);
@@ -221,7 +255,7 @@ function j(e, t) {
221
255
  }
222
256
  return n;
223
257
  }
224
- function M(e) {
258
+ function z(e) {
225
259
  let t = [];
226
260
  for (let [n, r] of e) {
227
261
  let e = o(n);
@@ -234,18 +268,15 @@ function M(e) {
234
268
  return t;
235
269
  }
236
270
  //#endregion
237
- //#region src/schema.utils.ts
238
- var N = "rxdb", P = "public", F = (e) => e && (e === N ? P : e);
239
- //#endregion
240
271
  //#region src/transform.ts
241
- function I(e, t) {
272
+ function B(e, t) {
242
273
  if (e == null) return e;
243
274
  switch (t.type) {
244
275
  case r.date: return e instanceof Date ? e : new Date(e);
245
276
  case r.keyValue:
246
277
  if (typeof e == "object" && t.properties) {
247
278
  let n = e, r = {};
248
- for (let e of t.properties) n[e.name] !== void 0 && (r[e.name] = I(n[e.name], e));
279
+ for (let e of t.properties) n[e.name] !== void 0 && (r[e.name] = B(n[e.name], e));
249
280
  return r;
250
281
  }
251
282
  return e;
@@ -256,58 +287,55 @@ function I(e, t) {
256
287
  default: return e;
257
288
  }
258
289
  }
259
- function L(e, t, n) {
290
+ function V(e, t, n) {
260
291
  let r = new e();
261
292
  for (let e of Object.keys(n)) {
262
293
  let i = t.propertyMap.get(e);
263
- r[e] = i ? I(n[e], i) : n[e];
294
+ r[e] = i ? B(n[e], i) : n[e];
264
295
  }
265
296
  return r;
266
297
  }
267
298
  //#endregion
268
299
  //#region src/SupabaseRepository.ts
269
- var R = class extends i {
300
+ var H = class extends i {
270
301
  adapter;
271
302
  metadata;
272
303
  constructor(e, t) {
273
304
  super(e.rxdb, t), this.adapter = e, this.metadata = o(t);
274
305
  }
275
306
  async find(e) {
276
- let t = this.extract_relation_fields(e.where), n = "*";
277
- if (t.size > 0) {
278
- let e = Array.from(t);
279
- n = `*, ${e.filter((t) => !e.some((e) => e !== t && e.startsWith(t + "."))).map((e) => this.build_relation_select(e)).join(", ")}`;
307
+ let t = e.where, n = this.extract_relation_fields(t), r = "*";
308
+ if (n.size > 0) {
309
+ let e = Array.from(n.keys());
310
+ r = `*, ${e.filter((t) => !e.some((e) => e !== t && e.startsWith(t + "."))).map((e) => this.build_relation_select(e, n.get(e) ?? !0)).join(", ")}`;
280
311
  }
281
- let r = () => {
282
- let t = this.get_client().select(n);
283
- if (t = T(t, e.where, this.metadata, this.adapter.rxdb.schemaManager), e.orderBy?.length) {
284
- for (let n of e.orderBy) t = t.order(n.field, { ascending: n.sort === "asc" });
285
- e.orderBy.some((e) => e.field === "id") || (t = t.order("id", { ascending: !0 }));
286
- }
287
- return t;
288
- }, i = 1e3, a = [], o = e.offset ?? 0, s = e.limit;
312
+ let i = () => {
313
+ let n = this.get_client().select(r);
314
+ if (n = M(n, t, this.metadata, this.adapter.rxdb.schemaManager), e.orderBy?.length) for (let t of e.orderBy) n = n.order(t.field, { ascending: t.sort === "asc" });
315
+ return e.orderBy?.some((e) => e.field === "id") || (n = n.order("id", { ascending: !0 })), n;
316
+ }, a = 1e3, o = [], s = e.offset ?? 0, c = e.limit;
289
317
  for (;;) {
290
- let e = s === void 0 ? i : Math.min(i, s);
318
+ let e = c === void 0 ? a : Math.min(a, c);
291
319
  if (e <= 0) break;
292
- let { data: t, error: n } = await r().range(o, o + e - 1);
320
+ let { data: t, error: n } = await i().range(s, s + e - 1);
293
321
  if (n) throw new g(`Failed to find entities: ${n.message}`);
294
- let c = t ?? [];
295
- if (a.push(...c), c.length < e || (o += c.length, s !== void 0 && (s -= c.length, s <= 0))) break;
322
+ let r = t ?? [];
323
+ if (o.push(...r), r.length < e || (s += r.length, c !== void 0 && (c -= r.length, c <= 0))) break;
296
324
  }
297
- return a.map((e) => L(this.EntityType, this.metadata, e));
325
+ return o.map((e) => V(this.EntityType, this.metadata, e));
298
326
  }
299
327
  async count(e) {
300
328
  if (e.groupBy) throw Error("groupBy not supported yet");
301
- let t = this.extract_relation_fields(e.where), n = "*";
302
- t.size > 0 && (n = `*, ${Array.from(t).map((e) => this.build_relation_select(e)).join(", ")}`);
303
- let r = this.get_client().select(n, {
329
+ let t = e.where, n = this.extract_relation_fields(t), r = "*";
330
+ n.size > 0 && (r = `*, ${Array.from(n).map(([e, t]) => this.build_relation_select(e, t)).join(", ")}`);
331
+ let i = this.get_client().select(r, {
304
332
  count: "exact",
305
333
  head: !0
306
334
  });
307
- r = T(r, e.where, this.metadata, this.adapter.rxdb.schemaManager);
308
- let { count: i, error: a } = await r;
309
- if (a) throw new g(`Failed to count entities: ${a.message || "unknown error"}`);
310
- return i ?? 0;
335
+ i = M(i, t, this.metadata, this.adapter.rxdb.schemaManager);
336
+ let { count: a, error: o } = await i;
337
+ if (o) throw new g(`Failed to count entities: ${o.message || "unknown error"}`);
338
+ return a ?? 0;
311
339
  }
312
340
  async create(e) {
313
341
  let t = { ...e }, n = this.rxdb.context.userId;
@@ -324,54 +352,61 @@ var R = class extends i {
324
352
  return i;
325
353
  }
326
354
  async remove(e) {
327
- let { error: t } = await this.get_client().delete().eq("id", e.id);
328
- if (t) throw new g(`Failed to remove entity: ${t.message}`);
355
+ let { data: t, error: n } = await this.get_client().delete().eq("id", e.id).select("id").single();
356
+ if (n) throw new g(`Failed to remove entity: ${n.message}`);
357
+ if (t?.id !== e.id) throw new g("Failed to remove entity: deleted row did not match");
329
358
  return e;
330
359
  }
331
360
  extract_relation_fields(e) {
332
- let t = /* @__PURE__ */ new Set(), n = (e, r = "") => {
333
- if (e?.rules) {
334
- for (let i of e.rules) if (s(i)) n(i, r);
335
- else if (typeof i.field == "string" && i.field.includes(".")) {
336
- let e = i.field.split(".");
337
- for (let n = 1; n < e.length; n++) {
338
- let i = e.slice(0, n).join(".");
339
- t.add(r ? `${r}.${i}` : i);
361
+ let t = /* @__PURE__ */ new Map(), n = (e, n) => {
362
+ (n || !t.has(e)) && t.set(e, n);
363
+ }, r = (e, t = "") => {
364
+ if (e?.rules) for (let i of e.rules) {
365
+ if (s(i)) {
366
+ r(i, t);
367
+ continue;
368
+ }
369
+ let e = i;
370
+ if (e.field.includes(".")) {
371
+ let r = e.field.split(".");
372
+ for (let e = 1; e < r.length; e++) {
373
+ let i = r.slice(0, e).join(".");
374
+ n(t ? `${t}.${i}` : i, !0);
340
375
  }
341
- } else if (i.operator === "exists" || i.operator === "notExists") {
342
- let e = String(i.field), a = r ? `${r}.${e}` : e;
343
- this.metadata.relationMap?.has(e) && t.add(a), "where" in i && i.where && n(i.where, a);
376
+ } else if (e.operator === "exists" || e.operator === "notExists") {
377
+ let i = e.field, a = t ? `${t}.${i}` : i;
378
+ this.metadata.relationMap?.has(i) && n(a, e.operator === "exists"), e.where && r(e.where, a);
344
379
  }
345
380
  }
346
381
  };
347
- return n(e), t;
348
- }
349
- build_relation_select(e) {
350
- let t = e.split(".");
351
- if (t.length === 1) return this.build_single_relation_select(t[0]);
352
- let n = [], r = this.metadata;
353
- for (let e of t) {
354
- let t = r.relationMap?.get(e);
382
+ return r(e), t;
383
+ }
384
+ build_relation_select(e, t) {
385
+ let n = e.split(".");
386
+ if (n.length === 1) return this.build_single_relation_select(n[0], t);
387
+ let r = [], i = this.metadata;
388
+ for (let e of n) {
389
+ let t = i.relationMap?.get(e);
355
390
  if (!t) return `${e}(id)`;
356
- let i = this.adapter.rxdb.schemaManager.getEntityMetadata(t.mappedEntity, t.mappedNamespace ?? "");
357
- n.push({
391
+ let n = this.adapter.rxdb.schemaManager.getEntityMetadata(t.mappedEntity, t.mappedNamespace ?? "");
392
+ r.push({
358
393
  relationName: e,
359
- targetTableName: i?.tableName ?? t.mappedEntity,
394
+ targetTableName: n?.tableName ?? t.mappedEntity,
360
395
  targetEntityName: t.mappedEntity,
361
396
  kind: t.kind,
362
- sourceEntityName: r.name,
363
- sourceTableName: r.tableName
364
- }), i && (r = i);
397
+ sourceEntityName: i.name,
398
+ sourceTableName: i.tableName
399
+ }), n && (i = n);
365
400
  }
366
- let i = this.build_relation_segment(n[n.length - 1], !0);
367
- for (let e = n.length - 2; e >= 0; e--) i = this.build_relation_segment(n[e], !0).replace("(*)", `(*, ${i})`);
368
- return i;
401
+ let a = this.build_relation_segment(r[r.length - 1], t);
402
+ for (let e = r.length - 2; e >= 0; e--) a = this.build_relation_segment(r[e], t).replace("(*)", `(*, ${a})`);
403
+ return a;
369
404
  }
370
- build_single_relation_select(e) {
371
- let t = this.metadata.relationMap?.get(e);
372
- if (!t) return `${e}(id)`;
373
- let n = this.adapter.rxdb.schemaManager.getEntityMetadata(t.mappedEntity, t.mappedNamespace ?? "")?.tableName ?? t.mappedEntity, r = this.metadata.tableName;
374
- return t.kind === "m:1" || t.kind === "1:1" ? `${e}:${n}!${`${r}_${e}Id_fkey`.toLowerCase()}(*)` : t.kind === "m:n" ? `${e}:${n}!${this.get_join_table_name(this.metadata.name, t.mappedEntity)}(*)` : `${e}:${n}(*)`;
405
+ build_single_relation_select(e, t) {
406
+ let n = this.metadata.relationMap?.get(e);
407
+ if (!n) return `${e}(id)`;
408
+ let r = this.adapter.rxdb.schemaManager.getEntityMetadata(n.mappedEntity, n.mappedNamespace ?? "")?.tableName ?? n.mappedEntity, i = this.metadata.tableName, a = t ? "!inner" : "";
409
+ return n.kind === "m:1" || n.kind === "1:1" ? `${e}:${r}!${`${i}_${e}Id_fkey`.toLowerCase()}${a}(*)` : n.kind === "m:n" ? `${e}:${r}!${this.get_join_table_name(this.metadata.name, n.mappedEntity)}${a}(*)` : `${e}:${r}${a}(*)`;
375
410
  }
376
411
  build_relation_segment(e, t) {
377
412
  let n = t ? "!inner" : "";
@@ -389,47 +424,29 @@ var R = class extends i {
389
424
  return [e, t].sort().join("_");
390
425
  }
391
426
  get_client() {
392
- let e = F(this.metadata.namespace);
427
+ let e = y(this.metadata.namespace);
393
428
  return e ? this.adapter.client.schema(e).from(this.metadata.tableName) : this.adapter.client.from(this.metadata.tableName);
394
429
  }
395
- }, z = class extends R {
430
+ }, U = class extends H {
396
431
  constructor(e, t) {
397
432
  super(e, t);
398
433
  }
399
434
  async findDescendants(e) {
400
- let { entityId: t, level: n = 100 } = e, { data: r, error: i } = await this.adapter.client.rpc(t ? "get_descendants" : "get_root_descendants", t ? {
401
- root_id: t,
402
- max_level: n
403
- } : { max_level: n });
404
- if (i) {
405
- if (i.message.includes("function") || i.message.includes("Could not find")) return this.findDescendantsFallback(e);
406
- throw new g(`Failed to find descendants: ${i.message}`);
407
- }
408
- return (r || []).map((e) => this.transformRowToEntity(e));
435
+ return this.findDescendantsFromTable(e);
409
436
  }
410
437
  async countDescendants(e) {
411
438
  let { entityId: t } = e, n = await this.findDescendants(e);
412
- return t ? n.length - 1 : n.length;
439
+ return t ? Math.max(0, n.length - 1) : n.length;
413
440
  }
414
441
  async findAncestors(e) {
415
- let { entityId: t, level: n = 100 } = e;
416
- if (!t) return [];
417
- let { data: r, error: i } = await this.adapter.client.rpc("get_ancestors", {
418
- node_id: t,
419
- max_level: n
420
- });
421
- if (i) {
422
- if (i.message.includes("function") || i.message.includes("Could not find")) return this.findAncestorsFallback(e);
423
- throw new g(`Failed to find ancestors: ${i.message}`);
424
- }
425
- return (r || []).map((e) => this.transformRowToEntity(e));
442
+ return this.findAncestorsFromTable(e);
426
443
  }
427
444
  async countAncestors(e) {
428
445
  let t = await this.findAncestors(e);
429
446
  return Math.max(0, t.length - 1);
430
447
  }
431
- async findDescendantsFallback(e) {
432
- let { entityId: t, level: n = 100 } = e, r = this.metadata.name, i = this.metadata.features?.tree?.hasChildren, a = F(this.metadata.namespace) ?? "public", o = this.adapter.client.schema(a).from(r), s = [], c = /* @__PURE__ */ new Set(), l = async (e) => {
448
+ async findDescendantsFromTable(e) {
449
+ let { entityId: t, level: n = 100 } = e, r = this.metadata.tableName, i = this.metadata.features?.tree?.hasChildren, a = y(this.metadata.namespace) ?? "public", o = this.adapter.client.schema(a).from(r), s = [], c = /* @__PURE__ */ new Set(), l = async (e) => {
433
450
  let { data: n, error: r } = await (e === void 0 ? t ? o.select("*").eq("id", t).limit(1) : o.select("*").is("parentId", null) : o.select("*").in("parentId", e));
434
451
  if (r) throw new g(`Failed to find descendants: ${r.message}`);
435
452
  return n ?? [];
@@ -440,7 +457,7 @@ var R = class extends i {
440
457
  return c.has(n) ? !1 : (c.add(n), e.push(n), !0);
441
458
  });
442
459
  if (t.length === 0) break;
443
- let r = d < n && e.length > 0 ? await l(e) : [], a = /* @__PURE__ */ new Map();
460
+ let r = (d < n || i) && e.length > 0 ? await l(e) : [], a = /* @__PURE__ */ new Map();
444
461
  for (let e of r) {
445
462
  let t = e.parentId;
446
463
  typeof t == "string" && a.set(t, (a.get(t) ?? 0) + 1);
@@ -453,14 +470,14 @@ var R = class extends i {
453
470
  }
454
471
  s.push(t);
455
472
  }
456
- u = r, d += 1;
473
+ u = d < n ? r : [], d += 1;
457
474
  }
458
475
  return s;
459
476
  }
460
- async findAncestorsFallback(e) {
477
+ async findAncestorsFromTable(e) {
461
478
  let { entityId: t, level: n = 100 } = e;
462
479
  if (!t) return [];
463
- let r = this.metadata.name, i = this.metadata.features?.tree?.hasChildren, a = F(this.metadata.namespace) ?? "public", { data: o, error: s } = await this.adapter.client.schema(a).from(r).select("*");
480
+ let r = this.metadata.tableName, i = this.metadata.features?.tree?.hasChildren, a = y(this.metadata.namespace) ?? "public", { data: o, error: s } = await this.adapter.client.schema(a).from(r).select("*");
464
481
  if (s) throw new g(`Failed to find ancestors: ${s.message}`);
465
482
  if (!o || o.length === 0) return [];
466
483
  let c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map();
@@ -484,9 +501,9 @@ var R = class extends i {
484
501
  }
485
502
  transformRowToEntity(e) {
486
503
  let t = { ...e };
487
- return delete t.level, L(this.EntityType, this.metadata, t);
504
+ return delete t.level, V(this.EntityType, this.metadata, t);
488
505
  }
489
- }, B = "supabase", V = [
506
+ }, W = "supabase", G = "2.88.0", K = [
490
507
  /invalid response was received from the upstream server/i,
491
508
  /fetch failed/i,
492
509
  /failed to fetch/i,
@@ -494,18 +511,18 @@ var R = class extends i {
494
511
  /upstream connect error/i,
495
512
  /connection terminated/i,
496
513
  /temporarily unavailable/i
497
- ], H = 3, U = 150, W = "rxdb_check_rls", G = 500, K = 5e3, q = new Set([
514
+ ], q = 3, J = 150, Y = "rxdb_check_rls", X = 500, Z = 5e3, Q = /* @__PURE__ */ new Set([
498
515
  "CHANNEL_ERROR",
499
516
  "TIMED_OUT",
500
517
  "CLOSED"
501
- ]);
502
- function J(e) {
518
+ ]), $ = 1e3, ee = 100;
519
+ function te(e) {
503
520
  return new Promise((t) => setTimeout(t, e));
504
521
  }
505
- function Y(e) {
506
- return V.some((t) => t.test(e));
522
+ function ne(e) {
523
+ return K.some((t) => t.test(e));
507
524
  }
508
- var X = class extends a {
525
+ var re = class extends a {
509
526
  options;
510
527
  #e;
511
528
  #t = null;
@@ -513,12 +530,18 @@ var X = class extends a {
513
530
  #r = 0;
514
531
  #i = !0;
515
532
  #a = !1;
516
- name = B;
533
+ name = W;
517
534
  get client() {
518
535
  return this.#e;
519
536
  }
520
537
  constructor(e, t) {
521
- super(e), this.options = t, this.#e = t.client ?? c(t.supabaseUrl, t.supabaseKey);
538
+ if (super(e), this.options = t, t.client) {
539
+ this.#e = t.client;
540
+ return;
541
+ }
542
+ let n = t.supabaseUrl?.trim(), r = t.supabaseKey?.trim();
543
+ if (!n || !r) throw new m("A non-empty supabaseUrl and supabaseKey are required when client is not supplied");
544
+ this.#e = c(n, r);
522
545
  }
523
546
  async connect() {
524
547
  return await this.#o(), this.#i = !0, this.#h(), this.#t ||= this.#f(), this;
@@ -530,30 +553,34 @@ var X = class extends a {
530
553
  }
531
554
  }
532
555
  async version() {
533
- return "2.86.0";
556
+ return G;
534
557
  }
535
558
  async saveMany(e) {
536
- return e.length === 0 ? [] : this.executeUpsert(A(e));
559
+ return e.length === 0 ? [] : this.executeUpsert(L(e));
537
560
  }
538
561
  async removeMany(e) {
539
- return e.length === 0 ? [] : this.executeDelete(A(e));
562
+ return e.length === 0 ? [] : this.executeDelete(L(e));
540
563
  }
541
564
  async mutations(e) {
542
- let t = this.rxdb.context.userId, n = [...j(e.create, t), ...j(e.update, t)], r = M(e.remove);
565
+ let t = this.rxdb.context.userId, n = [...R(e.create, t), ...R(e.update, t)], r = z(e.remove);
543
566
  if (n.length === 0 && r.length === 0) return [];
544
- let { data: i, error: a } = await this.#e.rpc("rxdb_mutations", {
545
- p_upserts: n,
546
- p_deletes: r
547
- });
548
- if (a) throw new g(`Transaction failed: ${a.message}`);
549
- let o = i?.upserted ?? [];
550
- for (let [, t] of e.remove) o.push(...t);
551
- return o;
567
+ let i = (await this.executeRetryableWrite("execute transaction", async () => {
568
+ let { data: e, error: t } = await this.#e.rpc("rxdb_mutations", {
569
+ p_upserts: n,
570
+ p_deletes: r
571
+ });
572
+ return {
573
+ data: e,
574
+ error: t
575
+ };
576
+ }))?.upserted ?? [];
577
+ for (let [, t] of e.remove) i.push(...t);
578
+ return i;
552
579
  }
553
580
  getRepository(e) {
554
581
  let t = this.repository_cache.get(e);
555
582
  if (t) return t;
556
- let n = o(e).features?.tree ? new z(this, e) : new R(this, e);
583
+ let n = o(e).features?.tree ? new U(this, e) : new H(this, e);
557
584
  return this.repository_cache.set(e, n), n;
558
585
  }
559
586
  async isTableExisted(e) {
@@ -566,30 +593,31 @@ var X = class extends a {
566
593
  throw new g(`Failed to check table existence: ${n.error?.message || `status ${n.status}`}`);
567
594
  }
568
595
  async pullChanges(e, t = 1e3, n, r, i) {
569
- let a = [], o;
570
- if (r && n?.length === 1) {
571
- let e = n[0];
572
- if (o = await this.#g(e, r), o.length === 0) return [];
596
+ if (t <= 0) return [];
597
+ let a = this.#g(n), o;
598
+ if (r && a?.length === 1 && (o = await this.#y(a[0], r), o.length === 0)) return [];
599
+ let s = o ? this.#v(o, ee) : [void 0], c = [];
600
+ for (let n of s) {
601
+ let r = this.#e.from("rxdb_change").select("*").gt("id", e).order("id", { ascending: !0 }).limit(t);
602
+ a?.length === 1 ? r = r.eq("namespace", a[0].namespace).eq("entity", a[0].entity) : a && a.length > 1 && (r = r.or(a.map((e) => this.#_(e)).join(","))), i && (r = r.eq("branchId", i)), n && (r = r.in("entityId", n));
603
+ let { data: o, error: s } = await r;
604
+ if (s) throw new g(`Failed to pull changes: ${s.message}`);
605
+ c.push(...(o ?? []).map((e) => ({
606
+ ...e,
607
+ createdAt: new Date(e.createdAt),
608
+ updatedAt: e.updatedAt ? new Date(e.updatedAt) : null
609
+ })));
573
610
  }
574
- let s = this.#e.from("rxdb_change").select("*").gt("id", e).order("id", { ascending: !0 }).limit(t);
575
- n && n.length > 0 && (s = s.in("entity", n)), i && (s = s.eq("branchId", i)), o && (s = s.in("entityId", o));
576
- let { data: c, error: l } = await s;
577
- if (l) throw new g(`Failed to pull changes: ${l.message}`);
578
- let u = (c ?? []).map((e) => ({
579
- ...e,
580
- createdAt: new Date(e.createdAt),
581
- updatedAt: e.updatedAt ? new Date(e.updatedAt) : null
582
- }));
583
- return a.push(...u), a;
611
+ return c.sort((e, t) => e.id - t.id).slice(0, t);
584
612
  }
585
613
  async getChangeCount(e, t, n) {
586
- let r = this.#e.from("rxdb_change").select("id", { count: "exact" }).gt("id", e);
587
- t && t.length > 0 && (r = r.in("entity", t)), n && (r = r.eq("branchId", n));
588
- let { data: i, count: a, error: o } = await r.order("id", { ascending: !1 }).limit(1);
589
- if (o) throw new g(`Failed to get change count: ${o.message}`);
614
+ let r = this.#g(t), i = this.#e.from("rxdb_change").select("id", { count: "exact" }).gt("id", e);
615
+ r?.length === 1 ? i = i.eq("namespace", r[0].namespace).eq("entity", r[0].entity) : r && r.length > 1 && (i = i.or(r.map((e) => this.#_(e)).join(","))), n && (i = i.eq("branchId", n));
616
+ let { data: a, count: o, error: s } = await i.order("id", { ascending: !1 }).limit(1);
617
+ if (s) throw new g(`Failed to get change count: ${s.message}`);
590
618
  return {
591
- count: a ?? 0,
592
- latestChangeId: a && a > 0 && i && i.length > 0 ? i[0].id : e
619
+ count: o ?? 0,
620
+ latestChangeId: o && o > 0 && a && a.length > 0 ? a[0].id : e
593
621
  };
594
622
  }
595
623
  async pushChanges(e) {
@@ -722,13 +750,18 @@ var X = class extends a {
722
750
  schema: n,
723
751
  ids: t
724
752
  };
725
- }) : [], { data: p, error: m } = await this.#e.rpc("rxdb_mutations", {
726
- p_upserts: d,
727
- p_deletes: f,
728
- p_changes: o,
729
- p_skip_sync: !0
753
+ }) : [], p = await this.executeRetryableWrite("merge changes", async () => {
754
+ let { data: e, error: t } = await this.#e.rpc("rxdb_mutations", {
755
+ p_upserts: d,
756
+ p_deletes: f,
757
+ p_changes: o,
758
+ p_skip_sync: !0
759
+ });
760
+ return {
761
+ data: e,
762
+ error: t
763
+ };
730
764
  });
731
- if (m) throw new g(`Failed to merge changes: ${m.message}`);
732
765
  return {
733
766
  maxChangeId: p?.max_change_id ?? void 0,
734
767
  changeIdMapping: p?.change_id_mapping ?? void 0
@@ -736,8 +769,14 @@ var X = class extends a {
736
769
  }
737
770
  async pullChangesBatch(e, t = 1e3, n) {
738
771
  if (e.length === 0) return [];
739
- if (e.length === 1 && (!n || n.length <= 1)) return this.pullChanges(e[0].sinceId, t, [e[0].entity], void 0, n?.[0]);
740
- let r = e.map((e) => `and(entity.eq.${e.entity},id.gt.${e.sinceId})`).join(","), i = this.#e.from("rxdb_change").select("*").or(r).order("id", { ascending: !0 }).limit(t);
772
+ if (e.length === 1 && (!n || n.length <= 1)) {
773
+ let r = e[0], i = r.namespace ? `${r.namespace}:${r.entity}` : r.entity;
774
+ return this.pullChanges(r.sinceId, t, [i], void 0, n?.[0]);
775
+ }
776
+ let r = e.map((e) => {
777
+ let t = e.namespace ? `${e.namespace}:${e.entity}` : e.entity, n = x(this.rxdb, t);
778
+ return `and(namespace.eq.${n.namespace},entity.eq.${n.entity},id.gt.${e.sinceId})`;
779
+ }).join(","), i = this.#e.from("rxdb_change").select("*").or(r).order("id", { ascending: !0 }).limit(t);
741
780
  n && n.length > 0 && (i = n.length === 1 ? i.eq("branchId", n[0]) : i.in("branchId", n));
742
781
  let { data: a, error: o } = await i;
743
782
  if (o) throw new g(`Failed to batch pull changes: ${o.message}`);
@@ -780,8 +819,8 @@ var X = class extends a {
780
819
  }
781
820
  fetchMetadata(e, t) {
782
821
  return l(() => {
783
- let n = this.rxdb.schemaManager.getEntityMetadata(e, "public")?.tableName ?? e, r = this.#e.from(n).select("id, updatedAt");
784
- return r = T(r, t), u(r).pipe(d(({ data: e, error: t }) => {
822
+ let n = x(this.rxdb, e), r = this.#e.schema(n.schema).from(n.tableName).select("id, updatedAt");
823
+ return r = M(r, t), u(r).pipe(d(({ data: e, error: t }) => {
785
824
  if (t) throw new g(`Failed to fetch metadata: ${t.message}`);
786
825
  return (e ?? []).map((e) => ({
787
826
  id: e.id,
@@ -793,24 +832,24 @@ var X = class extends a {
793
832
  findByIds(e, t) {
794
833
  return l(() => {
795
834
  if (t.length === 0) return f([]);
796
- let n = this.rxdb.schemaManager.getEntityMetadata(e, "public")?.tableName ?? e;
797
- return u(this.#e.from(n).select("*").in("id", t)).pipe(d(({ data: e, error: t }) => {
835
+ let n = x(this.rxdb, e);
836
+ return u(this.#e.schema(n.schema).from(n.tableName).select("*").in("id", t)).pipe(d(({ data: e, error: t }) => {
798
837
  if (t) throw new g(`Failed to find by ids: ${t.message}`);
799
838
  return e ?? [];
800
839
  }));
801
840
  });
802
841
  }
803
842
  getSchemaClient(e) {
804
- let t = F(e);
843
+ let t = y(e);
805
844
  return t ? this.#e.schema(t) : this.#e;
806
845
  }
807
846
  async executeRetryableWrite(e, t) {
808
847
  let n = "Unknown error";
809
- for (let r = 1; r <= H; r++) {
848
+ for (let r = 1; r <= q; r++) {
810
849
  let { data: i, error: a } = await t();
811
850
  if (!a) return i;
812
- if (n = a.message || "Unknown error", !Y(n) || r === H) throw new g(`Failed to ${e}: ${n}`);
813
- await J(U * r);
851
+ if (n = a.message || "Unknown error", !ne(n) || r === q) throw new g(`Failed to ${e}: ${n}`);
852
+ await te(J * r);
814
853
  }
815
854
  throw new g(`Failed to ${e}: ${n}`);
816
855
  }
@@ -848,42 +887,60 @@ var X = class extends a {
848
887
  }
849
888
  async #o() {
850
889
  if (this.#a || this.options.rlsCheck === !1) return;
851
- this.#a = !0;
852
890
  let e = this.#s(), t = this.#c(e.tables);
853
- if (t.length !== 0) try {
854
- let { data: n, error: r } = await this.#e.rpc(e.rpcName, { p_tables: t });
855
- if (r) {
856
- this.#d(this.#l(e.rpcName, r.message), e.failureMode);
857
- return;
858
- }
859
- let i = (Array.isArray(n) ? n : []).filter((e) => e.exists !== !1 && e.rlsEnabled !== !0);
860
- if (i.length > 0) {
861
- let t = i.map((e) => `${e.schema}.${e.table}`).sort().join(", ");
862
- this.#d(`[RxDB Supabase] RLS is disabled for tables: ${t}. Fix the policies before exposing this adapter to untrusted clients.`, e.failureMode);
863
- }
864
- } catch (t) {
865
- this.#d(this.#u(t), e.failureMode);
891
+ if (t.length === 0) {
892
+ this.#a = !0;
893
+ return;
894
+ }
895
+ let n = await Promise.resolve(this.#e.rpc(e.rpcName, { p_tables: t })).catch((t) => (this.#d(this.#u(t), e.failureMode), null));
896
+ if (!n) {
897
+ this.#a = !0;
898
+ return;
899
+ }
900
+ let { data: r, error: i } = n;
901
+ if (i) {
902
+ this.#d(this.#l(e.rpcName, i.message), e.failureMode), this.#a = !0;
903
+ return;
904
+ }
905
+ let a = new Map((Array.isArray(r) ? r : []).map((e) => [`${e.schema}:${e.table}`, e])), o = t.filter((e) => {
906
+ let t = a.get(`${e.schema ?? "public"}:${e.table}`);
907
+ return t?.exists !== !0 || t.rlsEnabled !== !0;
908
+ });
909
+ if (o.length > 0) {
910
+ let t = o.map((e) => `${e.schema}.${e.table}`).sort().join(", ");
911
+ this.#d(`[RxDB Supabase] RLS is disabled for tables: ${t}. Fix the policies before exposing this adapter to untrusted clients.`, e.failureMode);
866
912
  }
913
+ this.#a = !0;
867
914
  }
868
915
  #s() {
869
916
  return this.options.rlsCheck && typeof this.options.rlsCheck == "object" ? {
870
- rpcName: this.options.rlsCheck.rpcName ?? W,
917
+ rpcName: this.options.rlsCheck.rpcName ?? Y,
871
918
  failureMode: this.options.rlsCheck.failureMode ?? "warn",
872
919
  tables: this.options.rlsCheck.tables ?? []
873
920
  } : {
874
- rpcName: W,
921
+ rpcName: Y,
875
922
  failureMode: "warn",
876
923
  tables: []
877
924
  };
878
925
  }
879
926
  #c(e) {
880
- let t = e.length > 0 ? e : this.rxdb.config.entities.map((e) => {
881
- let t = o(e);
882
- return {
883
- schema: F(t.namespace),
884
- table: t.tableName
885
- };
886
- }), n = /* @__PURE__ */ new Map();
927
+ let t = e.length > 0 ? e : [
928
+ {
929
+ schema: "public",
930
+ table: "rxdb_change"
931
+ },
932
+ {
933
+ schema: "public",
934
+ table: "rxdb_branch"
935
+ },
936
+ ...this.rxdb.config.entities.map((e) => {
937
+ let t = o(e);
938
+ return {
939
+ schema: y(t.namespace),
940
+ table: t.tableName
941
+ };
942
+ })
943
+ ], n = /* @__PURE__ */ new Map();
887
944
  for (let e of t) {
888
945
  let t = e.schema ?? "public", r = `${t}:${e.table}`;
889
946
  n.set(r, {
@@ -909,21 +966,21 @@ var X = class extends a {
909
966
  event: "INSERT",
910
967
  schema: "public",
911
968
  table: "rxdb_change"
912
- }, (e) => v(this, e));
969
+ }, (e) => w(this, e));
913
970
  return e.subscribe((t, n) => {
914
971
  if (this.#t === e) {
915
972
  if (t === "SUBSCRIBED") {
916
973
  this.#r = 0;
917
974
  return;
918
975
  }
919
- n && console.error("Supabase Realtime subscription failed:", n), q.has(t) && this.#p(e, t, n?.message);
976
+ n && console.error("Supabase Realtime subscription failed:", n), Q.has(t) && this.#p(e, t, n?.message);
920
977
  }
921
978
  }), e;
922
979
  }
923
980
  #p(e, t, n) {
924
981
  if (!this.#i || this.#n || this.#t !== e) return;
925
982
  this.#r += 1;
926
- let r = Math.min(G * 2 ** (this.#r - 1), K), i = n?.trim();
983
+ let r = Math.min(X * 2 ** (this.#r - 1), Z), i = n?.trim();
927
984
  console.warn(`[RxDB Supabase] Realtime channel ${t} detected. Retrying in ${r}ms (attempt ${this.#r})${i ? `: ${i}` : ""}.`), this.#n = setTimeout(() => {
928
985
  this.#n = null, this.#m(e);
929
986
  }, r);
@@ -934,13 +991,29 @@ var X = class extends a {
934
991
  #h() {
935
992
  this.#n &&= (clearTimeout(this.#n), null);
936
993
  }
937
- async #g(e, t) {
938
- let n = this.rxdb.schemaManager.getEntityMetadata(e, "public")?.tableName ?? e, r = this.#e.from(n).select("id");
939
- r = T(r, t);
940
- let { data: i, error: a } = await r;
941
- if (a) throw new g(`Failed to query filtered entities: ${a.message}`);
942
- return (i ?? []).map((e) => e.id);
994
+ #g(e) {
995
+ if (e?.length) return e.map((e) => x(this.rxdb, e));
996
+ }
997
+ #_(e) {
998
+ return `and(namespace.eq.${e.namespace},entity.eq.${e.entity})`;
999
+ }
1000
+ #v(e, t) {
1001
+ let n = [];
1002
+ for (let r = 0; r < e.length; r += t) n.push(e.slice(r, r + t));
1003
+ return n;
1004
+ }
1005
+ async #y(e, t) {
1006
+ let n = [];
1007
+ for (let r = 0;; r += $) {
1008
+ let i = this.#e.schema(e.schema).from(e.tableName).select("id");
1009
+ i = M(i, t).order("id", { ascending: !0 }).range(r, r + $ - 1);
1010
+ let { data: a, error: o } = await i;
1011
+ if (o) throw new g(`Failed to query filtered entities: ${o.message}`);
1012
+ let s = a ?? [];
1013
+ if (n.push(...s.map((e) => String(e.id))), s.length < $) break;
1014
+ }
1015
+ return n;
943
1016
  }
944
1017
  };
945
1018
  //#endregion
946
- export { B as ADAPTER_NAME, X as RxDBAdapterSupabase, m as SupabaseConfigError, g as SupabaseDataError, h as SupabaseNetworkError, R as SupabaseRepository, p as SupabaseSyncError, z as SupabaseTreeRepository };
1019
+ export { W as ADAPTER_NAME, re as RxDBAdapterSupabase, G as SUPABASE_SDK_VERSION, m as SupabaseConfigError, g as SupabaseDataError, h as SupabaseNetworkError, H as SupabaseRepository, p as SupabaseSyncError, U as SupabaseTreeRepository };