@ragable/sdk 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1749,6 +1749,657 @@ var PostgrestTableApi = class {
1749
1749
  }
1750
1750
  };
1751
1751
 
1752
+ // src/collection-query.ts
1753
+ function flattenRecord(record) {
1754
+ return {
1755
+ ...record.data,
1756
+ id: record.id,
1757
+ createdAt: record.createdAt,
1758
+ updatedAt: record.updatedAt
1759
+ };
1760
+ }
1761
+ function parseColumns(columns) {
1762
+ const trimmed = (columns ?? "*").trim();
1763
+ if (!trimmed || trimmed === "*") return null;
1764
+ const fields = trimmed.split(",").map((c) => c.trim()).filter(Boolean).filter((c) => c !== "*");
1765
+ return fields.length > 0 ? fields : null;
1766
+ }
1767
+ function projectRow(row, fields) {
1768
+ if (!fields) return row;
1769
+ const out = {
1770
+ id: row.id,
1771
+ createdAt: row.createdAt,
1772
+ updatedAt: row.updatedAt
1773
+ };
1774
+ for (const field of fields) {
1775
+ if (field in row) out[field] = row[field];
1776
+ }
1777
+ return out;
1778
+ }
1779
+ var FILTER_OPS = /* @__PURE__ */ new Set([
1780
+ "eq",
1781
+ "neq",
1782
+ "gt",
1783
+ "gte",
1784
+ "lt",
1785
+ "lte",
1786
+ "like",
1787
+ "ilike",
1788
+ "startsWith",
1789
+ "endsWith",
1790
+ "in",
1791
+ "nin",
1792
+ "contains",
1793
+ "is",
1794
+ "exists"
1795
+ ]);
1796
+ function splitTopLevel(input) {
1797
+ const parts = [];
1798
+ let depth = 0;
1799
+ let inQuotes = false;
1800
+ let current = "";
1801
+ for (const ch of input) {
1802
+ if (ch === '"') inQuotes = !inQuotes;
1803
+ if (!inQuotes) {
1804
+ if (ch === "(") depth++;
1805
+ else if (ch === ")") depth = Math.max(0, depth - 1);
1806
+ if (ch === "," && depth === 0) {
1807
+ parts.push(current);
1808
+ current = "";
1809
+ continue;
1810
+ }
1811
+ }
1812
+ current += ch;
1813
+ }
1814
+ parts.push(current);
1815
+ return parts.map((p) => p.trim()).filter(Boolean);
1816
+ }
1817
+ function coerceOrValue(raw) {
1818
+ const v = raw.trim();
1819
+ if (v === "true") return true;
1820
+ if (v === "false") return false;
1821
+ if (v === "null") return null;
1822
+ if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
1823
+ if (v.length >= 2 && v.startsWith('"') && v.endsWith('"')) return v.slice(1, -1);
1824
+ return v;
1825
+ }
1826
+ function orSyntaxError(segment) {
1827
+ return new RagableError(
1828
+ `.or(): could not parse "${segment}". Expected "field.op.value" segments separated by commas, e.g. .or('done.eq.true,priority.gte.3') or .or('and(a.eq.1,b.eq.2),c.is.null'). Ops: ${[...FILTER_OPS].join(", ")} (prefix with "not." to negate).`,
1829
+ 400,
1830
+ { code: "SDK_COLLECTION_OR_SYNTAX" }
1831
+ );
1832
+ }
1833
+ function mergeCondition(group, field, op, value, negate) {
1834
+ const condition = negate ? { not: { [op]: value } } : { [op]: value };
1835
+ const existing = group[field];
1836
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
1837
+ const prev = existing;
1838
+ if (negate && prev.not && typeof prev.not === "object" && !Array.isArray(prev.not)) {
1839
+ group[field] = {
1840
+ ...prev,
1841
+ not: { ...prev.not, [op]: value }
1842
+ };
1843
+ return;
1844
+ }
1845
+ group[field] = { ...prev, ...condition };
1846
+ return;
1847
+ }
1848
+ group[field] = condition;
1849
+ }
1850
+ function parseOrCondition(segment, group) {
1851
+ const firstDot = segment.indexOf(".");
1852
+ if (firstDot <= 0) throw orSyntaxError(segment);
1853
+ const field = segment.slice(0, firstDot);
1854
+ let rest = segment.slice(firstDot + 1);
1855
+ let negate = false;
1856
+ if (rest.startsWith("not.")) {
1857
+ negate = true;
1858
+ rest = rest.slice(4);
1859
+ }
1860
+ const opDot = rest.indexOf(".");
1861
+ if (opDot <= 0) throw orSyntaxError(segment);
1862
+ const op = rest.slice(0, opDot);
1863
+ const rawValue = rest.slice(opDot + 1);
1864
+ if (!FILTER_OPS.has(op)) throw orSyntaxError(segment);
1865
+ let value;
1866
+ if (op === "in" || op === "nin") {
1867
+ const inner = rawValue.replace(/^\(/, "").replace(/\)$/, "");
1868
+ value = inner.trim().length === 0 ? [] : inner.split(",").map(coerceOrValue);
1869
+ } else {
1870
+ value = coerceOrValue(rawValue);
1871
+ }
1872
+ mergeCondition(group, field, op, value, negate);
1873
+ }
1874
+ function parseOrString(input) {
1875
+ const groups = [];
1876
+ for (const segment of splitTopLevel(input)) {
1877
+ if (/^and\(/.test(segment) && segment.endsWith(")")) {
1878
+ const inner = segment.slice(segment.indexOf("(") + 1, -1);
1879
+ const group = {};
1880
+ for (const condition of splitTopLevel(inner)) parseOrCondition(condition, group);
1881
+ if (Object.keys(group).length === 0) throw orSyntaxError(segment);
1882
+ groups.push(group);
1883
+ } else {
1884
+ const group = {};
1885
+ parseOrCondition(segment, group);
1886
+ groups.push(group);
1887
+ }
1888
+ }
1889
+ if (groups.length === 0) throw orSyntaxError(input);
1890
+ return groups;
1891
+ }
1892
+ var CollectionConditionBuilder = class {
1893
+ constructor() {
1894
+ __publicField(this, "filters", []);
1895
+ __publicField(this, "orGroups", null);
1896
+ __publicField(this, "signal");
1897
+ }
1898
+ /** `field = value` (or `IS NULL` when value is null). */
1899
+ eq(field, value) {
1900
+ return this.push(field, "eq", value);
1901
+ }
1902
+ /** `field != value` (null-aware). */
1903
+ neq(field, value) {
1904
+ return this.push(field, "neq", value);
1905
+ }
1906
+ gt(field, value) {
1907
+ return this.push(field, "gt", value);
1908
+ }
1909
+ gte(field, value) {
1910
+ return this.push(field, "gte", value);
1911
+ }
1912
+ lt(field, value) {
1913
+ return this.push(field, "lt", value);
1914
+ }
1915
+ lte(field, value) {
1916
+ return this.push(field, "lte", value);
1917
+ }
1918
+ /** SQL LIKE — you supply the `%` wildcards, e.g. `.like("title", "%report%")`. */
1919
+ like(field, pattern) {
1920
+ return this.push(field, "like", pattern);
1921
+ }
1922
+ /** Case-insensitive LIKE. */
1923
+ ilike(field, pattern) {
1924
+ return this.push(field, "ilike", pattern);
1925
+ }
1926
+ /** Prefix match; wildcard characters in `value` are matched literally. */
1927
+ startsWith(field, value) {
1928
+ return this.push(field, "startsWith", value);
1929
+ }
1930
+ /** Suffix match; wildcard characters in `value` are matched literally. */
1931
+ endsWith(field, value) {
1932
+ return this.push(field, "endsWith", value);
1933
+ }
1934
+ /** Value is one of `values`. */
1935
+ in(field, values) {
1936
+ return this.push(field, "in", values);
1937
+ }
1938
+ /** Value is NOT one of `values`. */
1939
+ nin(field, values) {
1940
+ return this.push(field, "nin", values);
1941
+ }
1942
+ /**
1943
+ * JSONB containment: array fields contain the given element(s), object
1944
+ * fields contain the given key/value pairs.
1945
+ * `.contains("tags", ["urgent"])`, `.contains("meta", { plan: "pro" })`.
1946
+ */
1947
+ contains(field, value) {
1948
+ return this.push(field, "contains", value);
1949
+ }
1950
+ /** Strict null / boolean check: `.is("archivedAt", null)`, `.is("done", true)`. */
1951
+ is(field, value) {
1952
+ return this.push(field, "is", value);
1953
+ }
1954
+ /** Whether the JSON key is present at all: `.exists("avatarUrl", false)`. */
1955
+ exists(field, present = true) {
1956
+ return this.push(field, "exists", present);
1957
+ }
1958
+ /** Negated condition: `.not("status", "eq", "archived")`. */
1959
+ not(field, op, value) {
1960
+ this.assertOp(op);
1961
+ this.filters.push({ field: String(field), op, value, not: true });
1962
+ return this;
1963
+ }
1964
+ /** Generic escape hatch, mirroring Supabase `.filter(column, op, value)`. */
1965
+ filter(field, op, value) {
1966
+ this.assertOp(op);
1967
+ return this.push(field, op, value);
1968
+ }
1969
+ /** Equality on every key of `query` (null values become IS NULL). */
1970
+ match(query) {
1971
+ for (const [field, value] of Object.entries(query)) {
1972
+ this.push(field, "eq", value);
1973
+ }
1974
+ return this;
1975
+ }
1976
+ /**
1977
+ * OR conditions, ANDed with the other filters. Accepts the Supabase string
1978
+ * grammar — `.or('done.eq.true,priority.gte.3')`, with `and(...)` for a
1979
+ * multi-condition branch — or an array of where-style objects:
1980
+ * `.or([{ done: true }, { priority: { gte: 3 } }])`.
1981
+ *
1982
+ * One `.or()` per query: the wire format carries a single disjunction.
1983
+ */
1984
+ or(conditions) {
1985
+ if (this.orGroups) {
1986
+ throw new RagableError(
1987
+ ".or() can only be used once per query. Combine branches in a single call: .or('a.eq.1,b.eq.2').",
1988
+ 400,
1989
+ { code: "SDK_COLLECTION_OR_TWICE" }
1990
+ );
1991
+ }
1992
+ this.orGroups = typeof conditions === "string" ? parseOrString(conditions) : conditions;
1993
+ if (!Array.isArray(this.orGroups) || this.orGroups.length === 0) {
1994
+ throw new RagableError(
1995
+ ".or() requires at least one condition.",
1996
+ 400,
1997
+ { code: "SDK_COLLECTION_OR_EMPTY" }
1998
+ );
1999
+ }
2000
+ return this;
2001
+ }
2002
+ abortSignal(signal) {
2003
+ this.signal = signal;
2004
+ return this;
2005
+ }
2006
+ get hasConditions() {
2007
+ return this.filters.length > 0 || (this.orGroups?.length ?? 0) > 0;
2008
+ }
2009
+ wireFilters() {
2010
+ return this.filters.map((f) => ({
2011
+ field: f.field,
2012
+ op: f.op,
2013
+ value: f.value,
2014
+ ...f.not ? { not: true } : {}
2015
+ }));
2016
+ }
2017
+ assertOp(op) {
2018
+ if (!FILTER_OPS.has(op)) {
2019
+ throw new RagableError(
2020
+ `Unknown filter operator "${op}". Use one of: ${[...FILTER_OPS].join(", ")}.`,
2021
+ 400,
2022
+ { code: "SDK_COLLECTION_BAD_OP" }
2023
+ );
2024
+ }
2025
+ }
2026
+ push(field, op, value) {
2027
+ this.filters.push({ field: String(field), op, value });
2028
+ return this;
2029
+ }
2030
+ };
2031
+ var CollectionSelectBuilder = class extends CollectionConditionBuilder {
2032
+ constructor(request, columns, options) {
2033
+ super();
2034
+ this.request = request;
2035
+ __publicField(this, "_limit");
2036
+ __publicField(this, "_offset");
2037
+ __publicField(this, "_order", []);
2038
+ __publicField(this, "columns");
2039
+ __publicField(this, "wantCount");
2040
+ __publicField(this, "headOnly");
2041
+ this.columns = parseColumns(columns);
2042
+ this.wantCount = options?.count === "exact";
2043
+ this.headOnly = options?.head === true;
2044
+ }
2045
+ /** Sort by a field. Call again to add secondary sort keys (max 4). */
2046
+ order(field, options) {
2047
+ this._order.push({
2048
+ field: String(field),
2049
+ direction: options?.ascending === true ? "asc" : "desc"
2050
+ });
2051
+ return this;
2052
+ }
2053
+ limit(n) {
2054
+ this._limit = n;
2055
+ return this;
2056
+ }
2057
+ offset(n) {
2058
+ this._offset = n;
2059
+ return this;
2060
+ }
2061
+ /** Rows `from`..`to` inclusive (zero-based), like Supabase `.range()`. */
2062
+ range(from, to) {
2063
+ this._offset = from;
2064
+ this._limit = Math.max(0, to - from + 1);
2065
+ return this;
2066
+ }
2067
+ then(onfulfilled, onrejected) {
2068
+ return this.execute().then(onfulfilled, onrejected);
2069
+ }
2070
+ /**
2071
+ * Exactly one row. 0 or >1 matching rows is an error (code PGRST116),
2072
+ * mirroring Supabase `.single()`.
2073
+ */
2074
+ async single() {
2075
+ const res = await this.executeRows(2);
2076
+ if (res.error) return { data: null, error: res.error };
2077
+ const rows = res.rows;
2078
+ if (rows.length !== 1) {
2079
+ return {
2080
+ data: null,
2081
+ error: new RagableError(
2082
+ "JSON object requested, multiple (or no) rows returned",
2083
+ 406,
2084
+ { code: "PGRST116", details: `The result contains ${rows.length} rows` }
2085
+ )
2086
+ };
2087
+ }
2088
+ return { data: rows[0], error: null };
2089
+ }
2090
+ /** One row or `null` — only >1 matching rows is an error. */
2091
+ async maybeSingle() {
2092
+ const res = await this.executeRows(2);
2093
+ if (res.error) return { data: null, error: res.error };
2094
+ const rows = res.rows;
2095
+ if (rows.length > 1) {
2096
+ return {
2097
+ data: null,
2098
+ error: new RagableError(
2099
+ "JSON object requested, multiple (or no) rows returned",
2100
+ 406,
2101
+ { code: "PGRST116", details: `The result contains ${rows.length} rows` }
2102
+ )
2103
+ };
2104
+ }
2105
+ return { data: rows[0] ?? null, error: null };
2106
+ }
2107
+ buildBody(limitOverride) {
2108
+ const body = {};
2109
+ const filters = this.wireFilters();
2110
+ if (filters.length > 0) body.filters = filters;
2111
+ if (this.orGroups) body.or = this.orGroups;
2112
+ const limit = limitOverride ?? (this.headOnly ? 0 : this._limit);
2113
+ if (limit !== void 0) body.limit = limit;
2114
+ if (this._offset !== void 0 && this._offset > 0) body.offset = this._offset;
2115
+ if (this._order.length === 1) {
2116
+ body.orderBy = this._order[0].field;
2117
+ body.orderDirection = this._order[0].direction;
2118
+ } else if (this._order.length > 1) {
2119
+ body.orderBy = this._order.map((o) => ({
2120
+ field: o.field,
2121
+ direction: o.direction
2122
+ }));
2123
+ }
2124
+ if (this.wantCount) body.count = true;
2125
+ return body;
2126
+ }
2127
+ async executeRows(limitOverride) {
2128
+ const result = await asPostgrestResponse(
2129
+ () => this.request(
2130
+ "POST",
2131
+ "/find",
2132
+ this.buildBody(limitOverride),
2133
+ this.signal
2134
+ )
2135
+ );
2136
+ if (result.error) return { error: result.error, rows: null, total: null };
2137
+ const payload = result.data;
2138
+ const records = Array.isArray(payload) ? payload : payload?.records ?? [];
2139
+ const total = Array.isArray(payload) ? null : payload?.total ?? null;
2140
+ const rows = records.map((r) => projectRow(flattenRecord(r), this.columns));
2141
+ return { error: null, rows, total };
2142
+ }
2143
+ async execute() {
2144
+ const res = await this.executeRows();
2145
+ if (res.error) return { data: null, error: res.error, count: null };
2146
+ return {
2147
+ data: this.headOnly ? [] : res.rows,
2148
+ error: null,
2149
+ count: res.total
2150
+ };
2151
+ }
2152
+ };
2153
+ var CollectionMutationReturning = class {
2154
+ constructor(run, columns) {
2155
+ this.run = run;
2156
+ this.columns = columns;
2157
+ }
2158
+ then(onfulfilled, onrejected) {
2159
+ return this.executeMany().then(onfulfilled, onrejected);
2160
+ }
2161
+ async executeMany() {
2162
+ const res = await this.run();
2163
+ if (res.error) return { data: null, error: res.error };
2164
+ const rows = (res.data ?? []).map(
2165
+ (r) => projectRow(flattenRecord(r), this.columns)
2166
+ );
2167
+ return { data: rows, error: null };
2168
+ }
2169
+ async single() {
2170
+ const many = await this.executeMany();
2171
+ if (many.error) return { data: null, error: many.error };
2172
+ const rows = many.data ?? [];
2173
+ if (rows.length !== 1) {
2174
+ return {
2175
+ data: null,
2176
+ error: new RagableError(
2177
+ "JSON object requested, multiple (or no) rows returned",
2178
+ 406,
2179
+ { code: "PGRST116", details: `The result contains ${rows.length} rows` }
2180
+ )
2181
+ };
2182
+ }
2183
+ return { data: rows[0], error: null };
2184
+ }
2185
+ async maybeSingle() {
2186
+ const many = await this.executeMany();
2187
+ if (many.error) return { data: null, error: many.error };
2188
+ const rows = many.data ?? [];
2189
+ if (rows.length > 1) {
2190
+ return {
2191
+ data: null,
2192
+ error: new RagableError(
2193
+ "JSON object requested, multiple (or no) rows returned",
2194
+ 406,
2195
+ { code: "PGRST116", details: `The result contains ${rows.length} rows` }
2196
+ )
2197
+ };
2198
+ }
2199
+ return { data: rows[0] ?? null, error: null };
2200
+ }
2201
+ };
2202
+ var CollectionUpdateBuilder = class extends CollectionConditionBuilder {
2203
+ constructor(request, patch) {
2204
+ super();
2205
+ this.request = request;
2206
+ this.patch = patch;
2207
+ __publicField(this, "_limit");
2208
+ }
2209
+ limit(n) {
2210
+ this._limit = n;
2211
+ return this;
2212
+ }
2213
+ select(columns = "*") {
2214
+ return new CollectionMutationReturning(
2215
+ () => this.execute(),
2216
+ parseColumns(columns)
2217
+ );
2218
+ }
2219
+ then(onfulfilled, onrejected) {
2220
+ return this.execute().then(
2221
+ (res) => res.error ? { data: null, error: res.error } : { data: null, error: null }
2222
+ ).then(onfulfilled, onrejected);
2223
+ }
2224
+ async execute() {
2225
+ if (!this.hasConditions) {
2226
+ return {
2227
+ data: null,
2228
+ error: new RagableError(
2229
+ "update() requires at least one filter \u2014 add .eq()/.match()/.or() before awaiting. To update every record, filter on a condition that always holds, e.g. .neq('id', null).",
2230
+ 400,
2231
+ { code: "SDK_COLLECTION_UPDATE_NO_FILTER" }
2232
+ )
2233
+ };
2234
+ }
2235
+ return asPostgrestResponse(
2236
+ () => this.request(
2237
+ "PATCH",
2238
+ "/records",
2239
+ {
2240
+ where: {},
2241
+ filters: this.wireFilters(),
2242
+ ...this.orGroups ? { or: this.orGroups } : {},
2243
+ patch: this.patch,
2244
+ ...this._limit !== void 0 ? { limit: this._limit } : {}
2245
+ },
2246
+ this.signal
2247
+ )
2248
+ );
2249
+ }
2250
+ };
2251
+ var CollectionDeleteBuilder = class extends CollectionConditionBuilder {
2252
+ constructor(request) {
2253
+ super();
2254
+ this.request = request;
2255
+ __publicField(this, "_limit");
2256
+ }
2257
+ limit(n) {
2258
+ this._limit = n;
2259
+ return this;
2260
+ }
2261
+ select(columns = "*") {
2262
+ return new CollectionMutationReturning(
2263
+ () => this.execute(),
2264
+ parseColumns(columns)
2265
+ );
2266
+ }
2267
+ then(onfulfilled, onrejected) {
2268
+ return this.execute().then(
2269
+ (res) => res.error ? { data: null, error: res.error } : { data: null, error: null }
2270
+ ).then(onfulfilled, onrejected);
2271
+ }
2272
+ async execute() {
2273
+ if (!this.hasConditions) {
2274
+ return {
2275
+ data: null,
2276
+ error: new RagableError(
2277
+ "delete() requires at least one filter \u2014 add .eq()/.match()/.or() before awaiting. To clear a collection, filter on a condition that always holds, e.g. .neq('id', null).",
2278
+ 400,
2279
+ { code: "SDK_COLLECTION_DELETE_NO_FILTER" }
2280
+ )
2281
+ };
2282
+ }
2283
+ const res = await asPostgrestResponse(
2284
+ () => this.request(
2285
+ "DELETE",
2286
+ "/records",
2287
+ {
2288
+ where: {},
2289
+ filters: this.wireFilters(),
2290
+ ...this.orGroups ? { or: this.orGroups } : {},
2291
+ ...this._limit !== void 0 ? { limit: this._limit } : {}
2292
+ },
2293
+ this.signal
2294
+ )
2295
+ );
2296
+ if (res.error) return { data: null, error: res.error };
2297
+ return { data: res.data.records ?? [], error: null };
2298
+ }
2299
+ };
2300
+ var CollectionInsertChain = class {
2301
+ constructor(request, rows, single) {
2302
+ this.request = request;
2303
+ this.rows = rows;
2304
+ this.single = single;
2305
+ __publicField(this, "_signal");
2306
+ }
2307
+ abortSignal(signal) {
2308
+ this._signal = signal;
2309
+ return this;
2310
+ }
2311
+ select(columns = "*") {
2312
+ return new CollectionMutationReturning(
2313
+ async () => {
2314
+ const res = await this.executeEnvelopes();
2315
+ if (res.error) return { data: null, error: res.error };
2316
+ return { data: res.data, error: null };
2317
+ },
2318
+ parseColumns(columns)
2319
+ );
2320
+ }
2321
+ then(onfulfilled, onrejected) {
2322
+ return this.executeEnvelopes().then((res) => {
2323
+ if (res.error) return { data: null, error: res.error };
2324
+ const envelopes = res.data;
2325
+ const resolved = this.single ? envelopes[0] ?? null : envelopes;
2326
+ return { data: resolved, error: null };
2327
+ }).then(onfulfilled, onrejected);
2328
+ }
2329
+ async executeEnvelopes() {
2330
+ if (this.rows.length === 0) return { data: [], error: null };
2331
+ if (this.single) {
2332
+ const res = await asPostgrestResponse(
2333
+ () => this.request(
2334
+ "POST",
2335
+ "/records",
2336
+ { data: this.rows[0] },
2337
+ this._signal
2338
+ )
2339
+ );
2340
+ if (res.error) return { data: null, error: res.error };
2341
+ return { data: [res.data], error: null };
2342
+ }
2343
+ return asPostgrestResponse(
2344
+ () => this.request(
2345
+ "POST",
2346
+ "/records/batch",
2347
+ { items: this.rows },
2348
+ this._signal
2349
+ )
2350
+ );
2351
+ }
2352
+ };
2353
+ var CollectionUpsertBuilder = class {
2354
+ constructor(request, rows, options) {
2355
+ this.request = request;
2356
+ this.rows = rows;
2357
+ this.options = options;
2358
+ __publicField(this, "_signal");
2359
+ }
2360
+ abortSignal(signal) {
2361
+ this._signal = signal;
2362
+ return this;
2363
+ }
2364
+ select(columns = "*") {
2365
+ return new CollectionMutationReturning(
2366
+ async () => {
2367
+ const res = await this.execute();
2368
+ if (res.error) return { data: null, error: res.error };
2369
+ return { data: res.data.records, error: null };
2370
+ },
2371
+ parseColumns(columns)
2372
+ );
2373
+ }
2374
+ then(onfulfilled, onrejected) {
2375
+ return this.execute().then((res) => {
2376
+ if (res.error) return { data: null, error: res.error };
2377
+ const { inserted, updated, skipped } = res.data;
2378
+ return { data: { inserted, updated, skipped }, error: null };
2379
+ }).then(onfulfilled, onrejected);
2380
+ }
2381
+ async execute() {
2382
+ if (this.rows.length === 0) {
2383
+ return {
2384
+ data: { records: [], inserted: 0, updated: 0, skipped: 0 },
2385
+ error: null
2386
+ };
2387
+ }
2388
+ return asPostgrestResponse(
2389
+ () => this.request(
2390
+ "POST",
2391
+ "/records/upsert",
2392
+ {
2393
+ items: this.rows,
2394
+ onConflict: this.options.onConflict ?? "id",
2395
+ ...this.options.ignoreDuplicates ? { ignoreDuplicates: true } : {}
2396
+ },
2397
+ this._signal
2398
+ )
2399
+ );
2400
+ }
2401
+ };
2402
+
1752
2403
  // src/auth-storage.ts
1753
2404
  var LocalStorageAdapter = class {
1754
2405
  getItem(key) {
@@ -2043,6 +2694,109 @@ var RagableAuth = class {
2043
2694
  this.emit("SIGNED_OUT", null);
2044
2695
  return { error: null };
2045
2696
  }
2697
+ // ── Password recovery & magic links ────────────────────────────────────────
2698
+ /**
2699
+ * Email a password-recovery link. The link points at `redirectTo` (or the
2700
+ * site's deployed domain when omitted) with `?token_hash=…&type=recovery`
2701
+ * appended. On that page, either:
2702
+ * - call {@link resetPassword} with the token and the new password, or
2703
+ * - call {@link verifyOtp} to sign the user in, then `updateUser({ password })`.
2704
+ *
2705
+ * Always resolves successfully for well-formed requests — whether the email
2706
+ * has an account is never revealed.
2707
+ */
2708
+ async resetPasswordForEmail(email, options) {
2709
+ return asPostgrestResponse(async () => {
2710
+ await this.fetchAuth("/forgot-password", "POST", {
2711
+ email,
2712
+ ...options?.redirectTo ? { redirectTo: options.redirectTo } : {}
2713
+ });
2714
+ return {};
2715
+ });
2716
+ }
2717
+ /**
2718
+ * Email a one-click sign-in (magic) link — passwordless auth. New addresses
2719
+ * get an account automatically unless `shouldCreateUser: false`. The emailed
2720
+ * link carries `?token_hash=…&type=magiclink`; complete sign-in on that page
2721
+ * with {@link verifyOtp}.
2722
+ */
2723
+ async signInWithOtp(params) {
2724
+ return asPostgrestResponse(async () => {
2725
+ await this.fetchAuth("/magic-link", "POST", {
2726
+ email: params.email,
2727
+ ...params.options?.emailRedirectTo ? { redirectTo: params.options.emailRedirectTo } : {},
2728
+ ...params.options?.shouldCreateUser === false ? { createUser: false } : {}
2729
+ });
2730
+ return { user: null, session: null };
2731
+ });
2732
+ }
2733
+ /**
2734
+ * Exchange an emailed `token_hash` for a session. Reads the token from the
2735
+ * URL your recovery / magic-link page receives:
2736
+ *
2737
+ * ```ts
2738
+ * const qs = new URLSearchParams(window.location.search);
2739
+ * const { data, error } = await client.auth.verifyOtp({
2740
+ * token_hash: qs.get("token_hash")!,
2741
+ * type: qs.get("type") as "recovery" | "magiclink",
2742
+ * });
2743
+ * ```
2744
+ *
2745
+ * Emits `SIGNED_IN` (and `PASSWORD_RECOVERY` for recovery tokens — listen
2746
+ * for it to route to your "choose a new password" screen).
2747
+ */
2748
+ async verifyOtp(params) {
2749
+ return asPostgrestResponse(async () => {
2750
+ const token = (params.token_hash ?? params.tokenHash ?? "").trim();
2751
+ if (!token) {
2752
+ throw new RagableError(
2753
+ "verifyOtp requires the token_hash from the emailed link.",
2754
+ 400,
2755
+ { code: "SDK_AUTH_MISSING_TOKEN_HASH" }
2756
+ );
2757
+ }
2758
+ const type = params.type === "email" ? "magiclink" : params.type;
2759
+ const raw = await this.fetchAuth("/verify-token", "POST", { token, type });
2760
+ const session = this.rawToSession(raw);
2761
+ await this.setSessionInternal(session, "SIGNED_IN");
2762
+ if (type === "recovery") this.emit("PASSWORD_RECOVERY", session);
2763
+ return { user: session.user, session };
2764
+ });
2765
+ }
2766
+ /**
2767
+ * One-shot recovery: verify the emailed recovery token, set the new
2768
+ * password, and sign the user in — no intermediate session juggling.
2769
+ *
2770
+ * ```ts
2771
+ * const qs = new URLSearchParams(window.location.search);
2772
+ * const { data, error } = await client.auth.resetPassword({
2773
+ * tokenHash: qs.get("token_hash")!,
2774
+ * newPassword: form.password,
2775
+ * });
2776
+ * ```
2777
+ *
2778
+ * Recovery links are single-use: once the password changes, the same link
2779
+ * is rejected.
2780
+ */
2781
+ async resetPassword(params) {
2782
+ return asPostgrestResponse(async () => {
2783
+ const token = (params.tokenHash ?? params.token_hash ?? "").trim();
2784
+ if (!token) {
2785
+ throw new RagableError(
2786
+ "resetPassword requires the token_hash from the recovery email link.",
2787
+ 400,
2788
+ { code: "SDK_AUTH_MISSING_TOKEN_HASH" }
2789
+ );
2790
+ }
2791
+ const raw = await this.fetchAuth("/reset-password", "POST", {
2792
+ token,
2793
+ password: params.newPassword
2794
+ });
2795
+ const session = this.rawToSession(raw);
2796
+ await this.setSessionInternal(session, "SIGNED_IN");
2797
+ return { user: session.user, session };
2798
+ });
2799
+ }
2046
2800
  async refreshSession(refreshToken) {
2047
2801
  return asPostgrestResponse(async () => {
2048
2802
  const token = refreshToken ?? this.currentSession?.refresh_token;
@@ -3254,6 +4008,22 @@ var RagableBrowserAuthClient = class {
3254
4008
  async signOut(_options) {
3255
4009
  return this.auth.signOut(_options);
3256
4010
  }
4011
+ /** Email a password-recovery link — see {@link RagableAuth.resetPasswordForEmail}. */
4012
+ async resetPasswordForEmail(email, options) {
4013
+ return this.auth.resetPasswordForEmail(email, options);
4014
+ }
4015
+ /** Email a magic sign-in link — see {@link RagableAuth.signInWithOtp}. */
4016
+ async signInWithOtp(params) {
4017
+ return this.auth.signInWithOtp(params);
4018
+ }
4019
+ /** Exchange an emailed token_hash for a session — see {@link RagableAuth.verifyOtp}. */
4020
+ async verifyOtp(params) {
4021
+ return this.auth.verifyOtp(params);
4022
+ }
4023
+ /** Verify a recovery token and set a new password in one call — see {@link RagableAuth.resetPassword}. */
4024
+ async resetPassword(params) {
4025
+ return this.auth.resetPassword(params);
4026
+ }
3257
4027
  async register(body) {
3258
4028
  return this.auth.register(body);
3259
4029
  }
@@ -3305,6 +4075,39 @@ var BrowserCollectionApi = class {
3305
4075
  this.database = database;
3306
4076
  this.name = name;
3307
4077
  this.databaseInstanceId = databaseInstanceId;
4078
+ /** Transport for the chainable builders, bound to this collection. */
4079
+ __publicField(this, "chainRequest", (method, path, body, signal) => this.database._requestCollection(
4080
+ method,
4081
+ `/${encodeURIComponent(this.name)}${path}`,
4082
+ body,
4083
+ this.databaseInstanceId,
4084
+ signal
4085
+ ));
4086
+ /**
4087
+ * Supabase-style chainable query. Rows come back flat (`id`, `createdAt`,
4088
+ * `updatedAt` merged into the document fields).
4089
+ *
4090
+ * ```ts
4091
+ * const { data, error, count } = await collections.todos
4092
+ * .select("*", { count: "exact" })
4093
+ * .eq("done", false)
4094
+ * .or("priority.gte.3,starred.eq.true")
4095
+ * .order("createdAt", { ascending: false })
4096
+ * .range(0, 19);
4097
+ * ```
4098
+ */
4099
+ __publicField(this, "select", (columns, options) => new CollectionSelectBuilder(this.chainRequest, columns, options));
4100
+ /**
4101
+ * Insert-or-update matched on `onConflict` (`"id"` by default, or any data
4102
+ * field, e.g. `{ onConflict: "slug" }`). Chain `.select()` for the affected
4103
+ * rows. Match-based (no unique indexes): concurrent upserts of the same new
4104
+ * value can both insert.
4105
+ */
4106
+ __publicField(this, "upsert", (values, options) => new CollectionUpsertBuilder(
4107
+ this.chainRequest,
4108
+ Array.isArray(values) ? values : [values],
4109
+ options ?? {}
4110
+ ));
3308
4111
  __publicField(this, "requestFind", (body) => asPostgrestResponse(
3309
4112
  () => this.database._requestCollection(
3310
4113
  "POST",
@@ -3348,14 +4151,20 @@ var BrowserCollectionApi = class {
3348
4151
  __publicField(this, "findUnique", async (args) => {
3349
4152
  return this.findFirst({ where: args.where });
3350
4153
  });
3351
- __publicField(this, "insert", (data) => asPostgrestResponse(
3352
- () => this.database._requestCollection(
3353
- "POST",
3354
- `/${encodeURIComponent(this.name)}/records`,
3355
- { data },
3356
- this.databaseInstanceId
3357
- )
3358
- ));
4154
+ /**
4155
+ * Insert one row or an array of rows. Chain `.select()` for the inserted
4156
+ * rows in flat shape, or await directly for the record envelope(s)
4157
+ * (back-compat extension; Supabase resolves to null without `.select()`).
4158
+ */
4159
+ __publicField(this, "insert", ((data) => {
4160
+ const isArray = Array.isArray(data);
4161
+ const rows = isArray ? data : [data];
4162
+ return new CollectionInsertChain(
4163
+ this.chainRequest,
4164
+ rows,
4165
+ !isArray
4166
+ );
4167
+ }));
3359
4168
  /**
3360
4169
  * Insert multiple rows in one request (server multi-value `INSERT`, single transaction).
3361
4170
  * Empty **`items`** resolves to an empty array. Max batch size is enforced on the server (500).
@@ -3369,16 +4178,28 @@ var BrowserCollectionApi = class {
3369
4178
  )
3370
4179
  ));
3371
4180
  /**
3372
- * Update rows matching `where` (JSON fields, plus envelope `id` / `createdAt` / `updatedAt`).
4181
+ * Two forms:
4182
+ * - `update(patch)` — Supabase-style chain: add filters, then await.
4183
+ * `update({ done: true }).eq("id", id)` (optionally `.select()`).
4184
+ * - `update(where, patch)` — legacy direct call, returns updated records.
3373
4185
  */
3374
- __publicField(this, "update", (where, patch, options) => asPostgrestResponse(
3375
- () => this.database._requestCollection(
3376
- "PATCH",
3377
- `/${encodeURIComponent(this.name)}/records`,
3378
- { where, patch, ...options?.limit ? { limit: options.limit } : {} },
3379
- this.databaseInstanceId
3380
- )
3381
- ));
4186
+ __publicField(this, "update", ((...args) => {
4187
+ if (args.length >= 2) {
4188
+ const [where, patch, options] = args;
4189
+ return asPostgrestResponse(
4190
+ () => this.database._requestCollection(
4191
+ "PATCH",
4192
+ `/${encodeURIComponent(this.name)}/records`,
4193
+ { where, patch, ...options?.limit ? { limit: options.limit } : {} },
4194
+ this.databaseInstanceId
4195
+ )
4196
+ );
4197
+ }
4198
+ return new CollectionUpdateBuilder(
4199
+ this.chainRequest,
4200
+ args[0]
4201
+ );
4202
+ }));
3382
4203
  /**
3383
4204
  * Like {@link BrowserCollectionApi.update} but the success payload includes
3384
4205
  * `meta.count` (number of rows returned from the update, bounded by `limit`).
@@ -3388,14 +4209,26 @@ var BrowserCollectionApi = class {
3388
4209
  if (r.error) return r;
3389
4210
  return { data: { records: r.data, meta: { count: r.data.length } }, error: null };
3390
4211
  });
3391
- __publicField(this, "delete", (where, options) => asPostgrestResponse(
3392
- () => this.database._requestCollection(
3393
- "DELETE",
3394
- `/${encodeURIComponent(this.name)}/records`,
3395
- { where, ...options?.limit ? { limit: options.limit } : {} },
3396
- this.databaseInstanceId
3397
- )
3398
- ));
4212
+ /**
4213
+ * Two forms:
4214
+ * - `delete()` — Supabase-style chain: add filters, then await.
4215
+ * `delete().eq("id", id)` (optionally `.select()`).
4216
+ * - `delete(where)` legacy direct call, returns `{ deleted, records }`.
4217
+ */
4218
+ __publicField(this, "delete", ((...args) => {
4219
+ if (args.length === 0) {
4220
+ return new CollectionDeleteBuilder(this.chainRequest);
4221
+ }
4222
+ const [where, options] = args;
4223
+ return asPostgrestResponse(
4224
+ () => this.database._requestCollection(
4225
+ "DELETE",
4226
+ `/${encodeURIComponent(this.name)}/records`,
4227
+ { where, ...options?.limit ? { limit: options.limit } : {} },
4228
+ this.databaseInstanceId
4229
+ )
4230
+ );
4231
+ }));
3399
4232
  /**
3400
4233
  * Like {@link BrowserCollectionApi.delete} but the success payload includes **`meta.count`**
3401
4234
  * (number of deleted rows), matching {@link BrowserCollectionApi.updateMany}.
@@ -3597,7 +4430,7 @@ var RagableBrowserDatabaseClient = class {
3597
4430
  toUrl(path) {
3598
4431
  return `${normalizeBrowserApiBase()}${path.startsWith("/") ? path : `/${path}`}`;
3599
4432
  }
3600
- async _requestCollection(method, path, body, databaseInstanceId) {
4433
+ async _requestCollection(method, path, body, databaseInstanceId, signal) {
3601
4434
  const gid = requireAuthGroupId(this.options);
3602
4435
  const token = await resolveDatabaseAuthBearer(this.options, this.ragableAuth);
3603
4436
  const id = databaseInstanceId?.trim() || this.options.databaseInstanceId?.trim();
@@ -3617,7 +4450,8 @@ var RagableBrowserDatabaseClient = class {
3617
4450
  {
3618
4451
  method,
3619
4452
  headers,
3620
- body: body !== void 0 ? JSON.stringify(body) : void 0
4453
+ body: body !== void 0 ? JSON.stringify(body) : void 0,
4454
+ ...signal ? { signal } : {}
3621
4455
  }
3622
4456
  );
3623
4457
  const payload = await parseMaybeJsonBody(response);
@@ -4648,6 +5482,12 @@ function createClient(options) {
4648
5482
  export {
4649
5483
  AuthBroadcastChannel,
4650
5484
  BrowserStorageBucketClient,
5485
+ CollectionDeleteBuilder,
5486
+ CollectionInsertChain,
5487
+ CollectionMutationReturning,
5488
+ CollectionSelectBuilder,
5489
+ CollectionUpdateBuilder,
5490
+ CollectionUpsertBuilder,
4651
5491
  CookieStorageAdapter,
4652
5492
  DEFAULT_RAGABLE_API_BASE,
4653
5493
  LocalStorageAdapter,
@@ -4708,6 +5548,7 @@ export {
4708
5548
  normalizeBrowserApiBase,
4709
5549
  parseAgentStreamAgentInfo,
4710
5550
  parseAgentStreamDone,
5551
+ parseOrString,
4711
5552
  parseSseDataLine,
4712
5553
  parseTransportResponse,
4713
5554
  readSseStream,
@@ -4720,4 +5561,3 @@ export {
4720
5561
  unwrapPostgrest,
4721
5562
  wrapStreamTextAsObject
4722
5563
  };
4723
- //# sourceMappingURL=index.mjs.map