@domql/utils 3.6.3 → 3.6.6

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.
@@ -4,6 +4,9 @@ var DomqlUtils = (() => {
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
7
10
  var __export = (target, all) => {
8
11
  for (var name in all)
9
12
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -18,6 +21,1510 @@ var DomqlUtils = (() => {
18
21
  };
19
22
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
23
 
24
+ // dist/esm/globals.js
25
+ var window3, document3;
26
+ var init_globals = __esm({
27
+ "dist/esm/globals.js"() {
28
+ window3 = globalThis;
29
+ document3 = window3.document;
30
+ }
31
+ });
32
+
33
+ // dist/esm/node.js
34
+ var init_node = __esm({
35
+ "dist/esm/node.js"() {
36
+ }
37
+ });
38
+
39
+ // dist/esm/types.js
40
+ var isObject2, isString2, isFunction2, isArray2;
41
+ var init_types = __esm({
42
+ "dist/esm/types.js"() {
43
+ isObject2 = (arg) => {
44
+ if (arg === null) return false;
45
+ return typeof arg === "object" && arg.constructor === Object;
46
+ };
47
+ isString2 = (arg) => typeof arg === "string";
48
+ isFunction2 = (arg) => typeof arg === "function";
49
+ isArray2 = (arg) => Array.isArray(arg);
50
+ }
51
+ });
52
+
53
+ // dist/esm/array.js
54
+ var init_array = __esm({
55
+ "dist/esm/array.js"() {
56
+ }
57
+ });
58
+
59
+ // dist/esm/string.js
60
+ var init_string = __esm({
61
+ "dist/esm/string.js"() {
62
+ }
63
+ });
64
+
65
+ // dist/esm/keys.js
66
+ var STATE_METHODS2, PROPS_METHODS2, METHODS2, METHODS_EXL2;
67
+ var init_keys = __esm({
68
+ "dist/esm/keys.js"() {
69
+ STATE_METHODS2 = /* @__PURE__ */ new Set([
70
+ "update",
71
+ "parse",
72
+ "clean",
73
+ "create",
74
+ "destroy",
75
+ "add",
76
+ "toggle",
77
+ "remove",
78
+ "apply",
79
+ "set",
80
+ "reset",
81
+ "replace",
82
+ "quietReplace",
83
+ "quietUpdate",
84
+ "applyReplace",
85
+ "applyFunction",
86
+ "keys",
87
+ "values",
88
+ "ref",
89
+ "rootUpdate",
90
+ "parentUpdate",
91
+ "parent",
92
+ "__element",
93
+ "__depends",
94
+ "__ref",
95
+ "__children",
96
+ "root",
97
+ "setByPath",
98
+ "setPathCollection",
99
+ "removeByPath",
100
+ "removePathCollection",
101
+ "getByPath"
102
+ ]);
103
+ PROPS_METHODS2 = /* @__PURE__ */ new Set(["update", "__element"]);
104
+ METHODS2 = /* @__PURE__ */ new Set([
105
+ "set",
106
+ "reset",
107
+ "update",
108
+ "remove",
109
+ "updateContent",
110
+ "removeContent",
111
+ "lookup",
112
+ "lookdown",
113
+ "lookdownAll",
114
+ "getRef",
115
+ "getPath",
116
+ "setNodeStyles",
117
+ "spotByPath",
118
+ "keys",
119
+ "parse",
120
+ "setProps",
121
+ "parseDeep",
122
+ "variables",
123
+ "if",
124
+ "log",
125
+ "verbose",
126
+ "warn",
127
+ "error",
128
+ "call",
129
+ "nextElement",
130
+ "previousElement",
131
+ "getRootState",
132
+ "getRoot",
133
+ "getRootData",
134
+ "getRootContext",
135
+ "getContext",
136
+ "getQuery",
137
+ "getDB",
138
+ "getChildren"
139
+ ]);
140
+ METHODS_EXL2 = /* @__PURE__ */ new Set([
141
+ "node",
142
+ "context",
143
+ "extends",
144
+ "__element",
145
+ "__ref",
146
+ ...METHODS2,
147
+ ...STATE_METHODS2,
148
+ ...PROPS_METHODS2
149
+ ]);
150
+ }
151
+ });
152
+
153
+ // dist/esm/object.js
154
+ var exec2;
155
+ var init_object = __esm({
156
+ "dist/esm/object.js"() {
157
+ init_types();
158
+ exec2 = (param, element, state, context) => {
159
+ if (isFunction2(param)) {
160
+ if (!element) return;
161
+ const result = param.call(
162
+ element,
163
+ element,
164
+ state || element.state,
165
+ context || element.context
166
+ );
167
+ if (result && typeof result.then === "function") {
168
+ let resolved;
169
+ result.then((value) => {
170
+ resolved = value;
171
+ });
172
+ return resolved;
173
+ }
174
+ return result;
175
+ }
176
+ return param;
177
+ };
178
+ }
179
+ });
180
+
181
+ // dist/esm/key.js
182
+ var init_key = __esm({
183
+ "dist/esm/key.js"() {
184
+ }
185
+ });
186
+
187
+ // dist/esm/env.js
188
+ var init_env = __esm({
189
+ "dist/esm/env.js"() {
190
+ }
191
+ });
192
+
193
+ // dist/esm/function.js
194
+ var init_function = __esm({
195
+ "dist/esm/function.js"() {
196
+ }
197
+ });
198
+
199
+ // dist/esm/if.js
200
+ var init_if = __esm({
201
+ "dist/esm/if.js"() {
202
+ }
203
+ });
204
+
205
+ // dist/esm/log.js
206
+ var init_log = __esm({
207
+ "dist/esm/log.js"() {
208
+ }
209
+ });
210
+
211
+ // dist/esm/cookie.js
212
+ var isMobile2;
213
+ var init_cookie = __esm({
214
+ "dist/esm/cookie.js"() {
215
+ isMobile2 = (() => typeof navigator === "undefined" ? false : /Mobi/.test(navigator.userAgent))();
216
+ }
217
+ });
218
+
219
+ // dist/esm/tags.js
220
+ var init_tags = __esm({
221
+ "dist/esm/tags.js"() {
222
+ }
223
+ });
224
+
225
+ // dist/esm/extends.js
226
+ var init_extends = __esm({
227
+ "dist/esm/extends.js"() {
228
+ }
229
+ });
230
+
231
+ // dist/esm/component.js
232
+ var init_component = __esm({
233
+ "dist/esm/component.js"() {
234
+ }
235
+ });
236
+
237
+ // dist/esm/props.js
238
+ var init_props = __esm({
239
+ "dist/esm/props.js"() {
240
+ }
241
+ });
242
+
243
+ // dist/esm/element.js
244
+ var init_element = __esm({
245
+ "dist/esm/element.js"() {
246
+ }
247
+ });
248
+
249
+ // dist/esm/state.js
250
+ var init_state = __esm({
251
+ "dist/esm/state.js"() {
252
+ }
253
+ });
254
+
255
+ // dist/esm/scope.js
256
+ var init_scope = __esm({
257
+ "dist/esm/scope.js"() {
258
+ }
259
+ });
260
+
261
+ // dist/esm/triggerEvent.js
262
+ var init_triggerEvent = __esm({
263
+ "dist/esm/triggerEvent.js"() {
264
+ }
265
+ });
266
+
267
+ // dist/esm/cache.js
268
+ var init_cache = __esm({
269
+ "dist/esm/cache.js"() {
270
+ }
271
+ });
272
+
273
+ // dist/esm/methods.js
274
+ var init_methods = __esm({
275
+ "dist/esm/methods.js"() {
276
+ }
277
+ });
278
+
279
+ // dist/esm/update.js
280
+ var init_update = __esm({
281
+ "dist/esm/update.js"() {
282
+ }
283
+ });
284
+
285
+ // dist/esm/index.js
286
+ var init_esm = __esm({
287
+ "dist/esm/index.js"() {
288
+ init_key();
289
+ init_env();
290
+ init_types();
291
+ init_object();
292
+ init_function();
293
+ init_array();
294
+ init_node();
295
+ init_if();
296
+ init_log();
297
+ init_string();
298
+ init_globals();
299
+ init_cookie();
300
+ init_tags();
301
+ init_component();
302
+ init_props();
303
+ init_extends();
304
+ init_element();
305
+ init_state();
306
+ init_keys();
307
+ init_scope();
308
+ init_methods();
309
+ init_cache();
310
+ init_update();
311
+ init_triggerEvent();
312
+ }
313
+ });
314
+
315
+ // ../../plugins/fetch/adapters/supabase.js
316
+ var supabase_exports = {};
317
+ __export(supabase_exports, {
318
+ setup: () => setup,
319
+ supabaseAdapter: () => supabaseAdapter
320
+ });
321
+ var setup, applyFilters, applyModifiers, supabaseAdapter;
322
+ var init_supabase = __esm({
323
+ "../../plugins/fetch/adapters/supabase.js"() {
324
+ "use strict";
325
+ setup = async ({ url, key, projectId, createClient, ...options }) => {
326
+ const supabaseUrl = url || projectId && `https://${projectId}.supabase.co`;
327
+ if (!supabaseUrl || !key) {
328
+ throw new Error("@symbo.ls/fetch supabase: url (or projectId) and key are required");
329
+ }
330
+ if (!createClient) {
331
+ const pkg = "@supabase/supabase-js";
332
+ const mod = await import(
333
+ /* webpackIgnore: true */
334
+ pkg
335
+ );
336
+ createClient = mod.createClient;
337
+ }
338
+ return supabaseAdapter(createClient(supabaseUrl, key, options));
339
+ };
340
+ applyFilters = (query, params) => {
341
+ if (!params) return query;
342
+ for (const key in params) {
343
+ const val = params[key];
344
+ if (val === null) {
345
+ query = query.is(key, null);
346
+ } else if (Array.isArray(val)) {
347
+ query = query.in(key, val);
348
+ } else if (typeof val === "object") {
349
+ for (const op in val) {
350
+ if (op === "gt") query = query.gt(key, val[op]);
351
+ else if (op === "gte") query = query.gte(key, val[op]);
352
+ else if (op === "lt") query = query.lt(key, val[op]);
353
+ else if (op === "lte") query = query.lte(key, val[op]);
354
+ else if (op === "neq") query = query.neq(key, val[op]);
355
+ else if (op === "like") query = query.like(key, val[op]);
356
+ else if (op === "ilike") query = query.ilike(key, val[op]);
357
+ else if (op === "in") query = query.in(key, val[op]);
358
+ else if (op === "is") query = query.is(key, val[op]);
359
+ else if (op === "contains") query = query.contains(key, val[op]);
360
+ else if (op === "containedBy") query = query.containedBy(key, val[op]);
361
+ else if (op === "textSearch") query = query.textSearch(key, val[op]);
362
+ }
363
+ } else {
364
+ query = query.eq(key, val);
365
+ }
366
+ }
367
+ return query;
368
+ };
369
+ applyModifiers = (query, { limit, offset, order, single } = {}) => {
370
+ if (order) {
371
+ if (Array.isArray(order)) {
372
+ for (const o of order) {
373
+ const by = typeof o === "string" ? o : o.by;
374
+ query = query.order(by, { ascending: o.asc !== false });
375
+ }
376
+ } else {
377
+ const orderBy = typeof order === "string" ? order : order.by;
378
+ query = query.order(orderBy, { ascending: order.asc !== false });
379
+ }
380
+ }
381
+ if (limit) query = query.limit(limit);
382
+ if (offset) query = query.range(offset, offset + (limit || 20) - 1);
383
+ if (single) query = query.single();
384
+ return query;
385
+ };
386
+ supabaseAdapter = (client) => ({
387
+ name: "supabase",
388
+ client,
389
+ // Auth
390
+ getSession: async () => {
391
+ const { data } = await client.auth.getSession();
392
+ return data?.session || null;
393
+ },
394
+ getUser: async () => {
395
+ const { data } = await client.auth.getUser();
396
+ return data?.user || null;
397
+ },
398
+ signIn: (credentials) => {
399
+ if (credentials.provider) {
400
+ return client.auth.signInWithOAuth({ provider: credentials.provider });
401
+ }
402
+ if (credentials.token) {
403
+ return client.auth.signInWithIdToken(credentials);
404
+ }
405
+ return client.auth.signInWithPassword(credentials);
406
+ },
407
+ signUp: (credentials) => client.auth.signUp(credentials),
408
+ signOut: () => client.auth.signOut(),
409
+ onAuthStateChange: (callback) => {
410
+ const { data: { subscription } } = client.auth.onAuthStateChange(
411
+ (event, session) => callback(event, session)
412
+ );
413
+ return () => subscription.unsubscribe();
414
+ },
415
+ // CRUD
416
+ select: async ({ from, select, params, ...modifiers }) => {
417
+ let q = client.from(from).select(select || "*");
418
+ q = applyFilters(q, params);
419
+ q = applyModifiers(q, modifiers);
420
+ return q;
421
+ },
422
+ rpc: ({ from, params }) => client.rpc(from, params),
423
+ insert: ({ from, data, select }) => client.from(from).insert(data).select(select || "*"),
424
+ update: ({ from, data, params, select }) => {
425
+ let q = client.from(from).update(data);
426
+ q = applyFilters(q, params);
427
+ return q.select(select || "*");
428
+ },
429
+ upsert: ({ from, data, select }) => client.from(from).upsert(data).select(select || "*"),
430
+ delete: ({ from, params }) => {
431
+ let q = client.from(from).delete();
432
+ q = applyFilters(q, params);
433
+ return q;
434
+ },
435
+ // Realtime
436
+ subscribe: ({ from, params, on }, callback) => {
437
+ const event = on || "*";
438
+ const channel = client.channel(`db-${from}-${Date.now()}`).on("postgres_changes", {
439
+ event,
440
+ schema: "public",
441
+ table: from,
442
+ ...params?.id ? { filter: `id=eq.${params.id}` } : {}
443
+ }, (payload) => callback(payload.new, payload.old, payload)).subscribe();
444
+ return () => client.removeChannel(channel);
445
+ },
446
+ // Storage
447
+ upload: ({ bucket, path, file, options }) => client.storage.from(bucket).upload(path, file, options),
448
+ download: ({ bucket, path }) => client.storage.from(bucket).download(path),
449
+ getPublicUrl: ({ bucket, path }) => client.storage.from(bucket).getPublicUrl(path)
450
+ });
451
+ }
452
+ });
453
+
454
+ // ../../plugins/fetch/adapters/rest.js
455
+ var rest_exports = {};
456
+ __export(rest_exports, {
457
+ restAdapter: () => restAdapter,
458
+ setup: () => setup2
459
+ });
460
+ var buildUrl, request, setup2, restAdapter;
461
+ var init_rest = __esm({
462
+ "../../plugins/fetch/adapters/rest.js"() {
463
+ "use strict";
464
+ buildUrl = (base, from, params) => {
465
+ const slash = from && !from.startsWith("/") ? "/" : "";
466
+ const url = new URL(`${base}${slash}${from}`);
467
+ if (params) {
468
+ for (const key in params) {
469
+ const val = params[key];
470
+ if (val !== void 0 && val !== null) {
471
+ url.searchParams.set(key, typeof val === "object" ? JSON.stringify(val) : val);
472
+ }
473
+ }
474
+ }
475
+ return url.toString();
476
+ };
477
+ request = async (url, options) => {
478
+ const res = await globalThis.fetch(url, options);
479
+ const contentType = res.headers.get("content-type");
480
+ const data = contentType && contentType.includes("json") ? await res.json() : await res.text();
481
+ return { data, error: res.ok ? null : data?.message || data?.error || res.statusText, status: res.status };
482
+ };
483
+ setup2 = async ({ url, headers, auth, fetchOptions }) => {
484
+ if (!url) throw new Error("@symbo.ls/fetch rest: url is required");
485
+ return restAdapter(url, headers, auth, fetchOptions);
486
+ };
487
+ restAdapter = (baseUrl, defaultHeaders = {}, authConfig, defaultFetchOptions = {}) => {
488
+ let token = authConfig?.token || null;
489
+ const getHeaders = (extra) => {
490
+ const h = { ...defaultHeaders, ...extra };
491
+ if (token) h.Authorization = `Bearer ${token}`;
492
+ return h;
493
+ };
494
+ const getJsonHeaders = (extra) => ({ ...getHeaders(extra), "Content-Type": "application/json" });
495
+ const getFetchOptions = (opts) => ({ ...defaultFetchOptions, ...opts });
496
+ const resolveUrl = (from, base) => {
497
+ const b = base || baseUrl;
498
+ if (from && (from.startsWith("http://") || from.startsWith("https://"))) return from;
499
+ const slash = from && !from.startsWith("/") ? "/" : "";
500
+ return `${b}${slash}${from || ""}`;
501
+ };
502
+ const adapter = {
503
+ name: "rest",
504
+ // Auth
505
+ setToken: (t) => {
506
+ token = t;
507
+ },
508
+ getSession: async () => {
509
+ if (!authConfig?.sessionUrl) {
510
+ return token ? { token } : null;
511
+ }
512
+ const result = await request(
513
+ resolveUrl(authConfig.sessionUrl, authConfig.baseUrl),
514
+ getFetchOptions({ headers: getHeaders() })
515
+ );
516
+ return result.error ? null : result.data;
517
+ },
518
+ signIn: async (credentials) => {
519
+ if (!authConfig?.signInUrl) throw new Error("rest: auth.signInUrl not configured");
520
+ const result = await request(resolveUrl(authConfig.signInUrl, authConfig.baseUrl), getFetchOptions({
521
+ method: "POST",
522
+ headers: getJsonHeaders(),
523
+ body: JSON.stringify(credentials)
524
+ }));
525
+ if (result.data?.token) token = result.data.token;
526
+ return result;
527
+ },
528
+ signOut: async () => {
529
+ if (authConfig?.signOutUrl) {
530
+ await request(resolveUrl(authConfig.signOutUrl, authConfig.baseUrl), getFetchOptions({
531
+ method: "POST",
532
+ headers: getHeaders()
533
+ }));
534
+ }
535
+ token = null;
536
+ return { error: null };
537
+ },
538
+ // CRUD
539
+ select: ({ from, params, select, limit, offset, order, single, headers, baseUrl: fromBase }) => {
540
+ const allParams = { ...params };
541
+ if (select) allParams.select = select;
542
+ if (limit) allParams.limit = limit;
543
+ if (offset) allParams.offset = offset;
544
+ if (single) allParams.single = true;
545
+ if (order) {
546
+ if (typeof order === "string") {
547
+ allParams.order = order;
548
+ } else if (Array.isArray(order)) {
549
+ allParams.order = order.map((o) => `${o.by}:${o.asc === false ? "desc" : "asc"}`).join(",");
550
+ } else if (order.by) {
551
+ allParams.order = `${order.by}:${order.asc === false ? "desc" : "asc"}`;
552
+ }
553
+ }
554
+ return request(
555
+ buildUrl(fromBase || baseUrl, from || "", allParams),
556
+ getFetchOptions({ headers: getHeaders(headers) })
557
+ );
558
+ },
559
+ rpc: ({ from, params, headers, baseUrl: fromBase }) => request(resolveUrl(`rpc/${from}`, fromBase), getFetchOptions({
560
+ method: "POST",
561
+ headers: getJsonHeaders(headers),
562
+ body: JSON.stringify(params)
563
+ })),
564
+ insert: ({ from, data, headers, baseUrl: fromBase }) => request(resolveUrl(from, fromBase), getFetchOptions({
565
+ method: "POST",
566
+ headers: getJsonHeaders(headers),
567
+ body: JSON.stringify(data)
568
+ })),
569
+ update: ({ from, data, params, method, headers, baseUrl: fromBase }) => {
570
+ const id = params?.id || data?.id;
571
+ const path = id ? `${from}/${id}` : from;
572
+ return request(resolveUrl(path, fromBase), getFetchOptions({
573
+ method: method || "PATCH",
574
+ headers: getJsonHeaders(headers),
575
+ body: JSON.stringify(data)
576
+ }));
577
+ },
578
+ delete: ({ from, params, headers, baseUrl: fromBase }) => {
579
+ const id = params?.id;
580
+ const path = id ? `${from}/${id}` : from;
581
+ return request(resolveUrl(path, fromBase), getFetchOptions({
582
+ method: "DELETE",
583
+ headers: getHeaders(headers)
584
+ }));
585
+ }
586
+ };
587
+ return adapter;
588
+ };
589
+ }
590
+ });
591
+
592
+ // ../../plugins/fetch/adapters/local.js
593
+ var local_exports = {};
594
+ __export(local_exports, {
595
+ localAdapter: () => localAdapter,
596
+ setup: () => setup3
597
+ });
598
+ var matchesParams, applyModifiers2, setup3, localAdapter;
599
+ var init_local = __esm({
600
+ "../../plugins/fetch/adapters/local.js"() {
601
+ "use strict";
602
+ matchesParams = (item, params) => {
603
+ if (!params) return true;
604
+ for (const key in params) {
605
+ const val = params[key];
606
+ if (val === null) {
607
+ if (item[key] !== null && item[key] !== void 0) return false;
608
+ } else if (Array.isArray(val)) {
609
+ if (!val.includes(item[key])) return false;
610
+ } else if (typeof val === "object") {
611
+ for (const op in val) {
612
+ if (op === "gt" && !(item[key] > val[op])) return false;
613
+ if (op === "gte" && !(item[key] >= val[op])) return false;
614
+ if (op === "lt" && !(item[key] < val[op])) return false;
615
+ if (op === "lte" && !(item[key] <= val[op])) return false;
616
+ if (op === "neq" && item[key] === val[op]) return false;
617
+ if (op === "like" && !String(item[key]).includes(val[op])) return false;
618
+ }
619
+ } else if (item[key] !== val) {
620
+ return false;
621
+ }
622
+ }
623
+ return true;
624
+ };
625
+ applyModifiers2 = (items, { order, limit, offset, single }) => {
626
+ let result = [...items];
627
+ if (order) {
628
+ const by = typeof order === "string" ? order : order.by;
629
+ const asc = order.asc !== false;
630
+ result.sort((a, b) => {
631
+ if (a[by] < b[by]) return asc ? -1 : 1;
632
+ if (a[by] > b[by]) return asc ? 1 : -1;
633
+ return 0;
634
+ });
635
+ }
636
+ if (offset) result = result.slice(offset);
637
+ if (limit) result = result.slice(0, limit);
638
+ if (single) return { data: result[0] || null, error: null };
639
+ return { data: result, error: null };
640
+ };
641
+ setup3 = async ({ data, ...options }) => localAdapter(data, options);
642
+ localAdapter = (initialData = {}, options = {}) => {
643
+ const store = {};
644
+ const listeners = {};
645
+ const persist = options.persist !== false && typeof localStorage !== "undefined";
646
+ const prefix = options.prefix || "smbls_db_";
647
+ const getTable = (name) => {
648
+ if (!store[name]) {
649
+ if (persist) {
650
+ try {
651
+ const saved = localStorage.getItem(prefix + name);
652
+ store[name] = saved ? JSON.parse(saved) : initialData[name] || [];
653
+ } catch {
654
+ store[name] = initialData[name] || [];
655
+ }
656
+ } else {
657
+ store[name] = initialData[name] || [];
658
+ }
659
+ }
660
+ return store[name];
661
+ };
662
+ const save = (name) => {
663
+ if (persist) {
664
+ try {
665
+ localStorage.setItem(prefix + name, JSON.stringify(store[name]));
666
+ } catch {
667
+ }
668
+ }
669
+ };
670
+ const notify = (name, event, newItem, oldItem) => {
671
+ const fns = listeners[name];
672
+ if (!fns) return;
673
+ for (const fn of fns) fn(newItem, oldItem, { event, table: name });
674
+ };
675
+ let idCounter = Date.now();
676
+ return {
677
+ name: "local",
678
+ store,
679
+ select: async ({ from, params, ...modifiers }) => {
680
+ const table = getTable(from);
681
+ const filtered = table.filter((item) => matchesParams(item, params));
682
+ return applyModifiers2(filtered, modifiers);
683
+ },
684
+ insert: async ({ from, data }) => {
685
+ const table = getTable(from);
686
+ const items = Array.isArray(data) ? data : [data];
687
+ const inserted = items.map((item) => {
688
+ const row = { id: item.id || ++idCounter, ...item };
689
+ table.push(row);
690
+ return row;
691
+ });
692
+ save(from);
693
+ for (const row of inserted) notify(from, "INSERT", row, null);
694
+ return { data: Array.isArray(data) ? inserted : inserted[0], error: null };
695
+ },
696
+ update: async ({ from, data, params }) => {
697
+ const table = getTable(from);
698
+ const updated = [];
699
+ for (let i = 0; i < table.length; i++) {
700
+ if (matchesParams(table[i], params)) {
701
+ const old = { ...table[i] };
702
+ Object.assign(table[i], data);
703
+ updated.push(table[i]);
704
+ notify(from, "UPDATE", table[i], old);
705
+ }
706
+ }
707
+ save(from);
708
+ return { data: updated, error: null };
709
+ },
710
+ delete: async ({ from, params }) => {
711
+ const table = getTable(from);
712
+ const removed = [];
713
+ for (let i = table.length - 1; i >= 0; i--) {
714
+ if (matchesParams(table[i], params)) {
715
+ removed.push(table[i]);
716
+ table.splice(i, 1);
717
+ notify(from, "DELETE", null, removed[removed.length - 1]);
718
+ }
719
+ }
720
+ save(from);
721
+ return { data: removed, error: null };
722
+ },
723
+ subscribe: ({ from, on }, callback) => {
724
+ if (!listeners[from]) listeners[from] = [];
725
+ const fn = (newItem, oldItem, payload) => {
726
+ if (on && on !== "*" && on !== payload.event) return;
727
+ callback(newItem, oldItem, payload);
728
+ };
729
+ listeners[from].push(fn);
730
+ return () => {
731
+ const idx = listeners[from].indexOf(fn);
732
+ if (idx > -1) listeners[from].splice(idx, 1);
733
+ };
734
+ }
735
+ };
736
+ };
737
+ }
738
+ });
739
+
740
+ // ../../plugins/fetch/index.js
741
+ var fetch_exports = {};
742
+ __export(fetch_exports, {
743
+ createAdapter: () => createAdapter,
744
+ default: () => fetch_default,
745
+ executeFetch: () => executeFetch,
746
+ initAdapterAuth: () => initAdapterAuth,
747
+ parseDuration: () => parseDuration,
748
+ queryClient: () => queryClient,
749
+ registerAdapter: () => registerAdapter,
750
+ resolveDb: () => resolveDb
751
+ });
752
+ var ADAPTER_METHODS, BUILTIN_ADAPTERS, registerAdapter, createAdapter, resolveDb, parseDuration, cacheStore, querySubscribers, activeQueries, buildCacheKey, getCacheEntry, setCacheEntry, invalidateCache, removeCache, parseCacheConfig, gcTimer, startGC, DEFAULT_RETRY, DEFAULT_RETRY_DELAY, resolveRetryConfig, withRetry, globalListeners, globalListenersAttached, attachGlobalListeners, resolveFetchConfig, resolveParamsSync, resolveParams, initAdapterAuth, resolveAdapter, triggerCallback, collectFormData, updateElementState, setFetchStatus, runFetch, bindEvent, bindAutoRefetch, applyOptimisticUpdate, rollbackOptimistic, runMutation, executeFetch, queryClient, fetch_default;
753
+ var init_fetch = __esm({
754
+ "../../plugins/fetch/index.js"() {
755
+ "use strict";
756
+ init_esm();
757
+ ADAPTER_METHODS = ["select", "rpc", "insert", "update", "delete", "subscribe"];
758
+ BUILTIN_ADAPTERS = {
759
+ supabase: () => Promise.resolve().then(() => (init_supabase(), supabase_exports)),
760
+ rest: () => Promise.resolve().then(() => (init_rest(), rest_exports)),
761
+ local: () => Promise.resolve().then(() => (init_local(), local_exports))
762
+ };
763
+ registerAdapter = (name, loader) => {
764
+ BUILTIN_ADAPTERS[name] = loader;
765
+ };
766
+ createAdapter = (config) => {
767
+ const adapter = {};
768
+ for (const method of ADAPTER_METHODS) {
769
+ if (config[method]) adapter[method] = config[method];
770
+ }
771
+ adapter.name = config.name || "custom";
772
+ return adapter;
773
+ };
774
+ resolveDb = async (config) => {
775
+ if (!config) return null;
776
+ if (typeof config.select === "function") return config;
777
+ const { adapter, ...options } = config;
778
+ const name = typeof adapter === "string" ? adapter : typeof config === "string" ? config : null;
779
+ if (!name) return null;
780
+ const loader = BUILTIN_ADAPTERS[name];
781
+ if (!loader) throw new Error(`Unknown db adapter: "${name}". Use registerAdapter() for adapters with optional deps.`);
782
+ const mod = await loader();
783
+ return mod.setup(options);
784
+ };
785
+ parseDuration = (val) => {
786
+ if (!val) return 0;
787
+ if (typeof val === "number") return val;
788
+ const match = val.match(/^(\d+)(ms|s|m|h)$/);
789
+ if (!match) return 0;
790
+ const n = parseInt(match[1]);
791
+ const unit = match[2];
792
+ if (unit === "ms") return n;
793
+ if (unit === "s") return n * 1e3;
794
+ if (unit === "m") return n * 6e4;
795
+ if (unit === "h") return n * 36e5;
796
+ return 0;
797
+ };
798
+ cacheStore = /* @__PURE__ */ new Map();
799
+ querySubscribers = /* @__PURE__ */ new Map();
800
+ activeQueries = /* @__PURE__ */ new Map();
801
+ buildCacheKey = (config) => {
802
+ if (config.cache?.key) return config.cache.key;
803
+ const params = resolveParamsSync(config.params);
804
+ return `${config.from}:${config.method}:${JSON.stringify(params || "")}`;
805
+ };
806
+ getCacheEntry = (key) => cacheStore.get(key) || null;
807
+ setCacheEntry = (key, data, error2) => {
808
+ const existing = cacheStore.get(key);
809
+ const entry = {
810
+ data,
811
+ error: error2,
812
+ time: Date.now(),
813
+ stale: false
814
+ };
815
+ cacheStore.set(key, entry);
816
+ const subs = querySubscribers.get(key);
817
+ if (subs) {
818
+ for (const sub of subs) {
819
+ if (isFunction2(sub)) sub(entry);
820
+ }
821
+ }
822
+ return entry;
823
+ };
824
+ invalidateCache = (key) => {
825
+ if (key) {
826
+ const entry = cacheStore.get(key);
827
+ if (entry) entry.stale = true;
828
+ return;
829
+ }
830
+ for (const [, entry] of cacheStore) {
831
+ entry.stale = true;
832
+ }
833
+ };
834
+ removeCache = (key) => {
835
+ if (key) {
836
+ cacheStore.delete(key);
837
+ return;
838
+ }
839
+ cacheStore.clear();
840
+ };
841
+ parseCacheConfig = (cache2) => {
842
+ if (!cache2 && cache2 !== false) return { staleTime: 6e4, gcTime: 3e5 };
843
+ if (cache2 === false) return null;
844
+ if (cache2 === true) return { staleTime: 6e4, gcTime: 3e5 };
845
+ if (typeof cache2 === "number") return { staleTime: cache2, gcTime: Math.max(cache2 * 5, 3e5) };
846
+ if (isString2(cache2)) return { staleTime: parseDuration(cache2), gcTime: 3e5 };
847
+ return {
848
+ staleTime: parseDuration(cache2.stale || cache2.staleTime) || 6e4,
849
+ gcTime: parseDuration(cache2.gc || cache2.gcTime || cache2.expire) || 3e5,
850
+ key: cache2.key
851
+ };
852
+ };
853
+ gcTimer = null;
854
+ startGC = () => {
855
+ if (gcTimer) return;
856
+ gcTimer = setInterval(() => {
857
+ const now = Date.now();
858
+ for (const [key, entry] of cacheStore) {
859
+ const subs = querySubscribers.get(key);
860
+ const hasSubscribers = subs && subs.size > 0;
861
+ if (!hasSubscribers && now - entry.time > (entry.gcTime || 3e5)) {
862
+ cacheStore.delete(key);
863
+ }
864
+ }
865
+ }, 3e4);
866
+ if (gcTimer.unref) gcTimer.unref();
867
+ };
868
+ startGC();
869
+ DEFAULT_RETRY = 3;
870
+ DEFAULT_RETRY_DELAY = (attempt) => Math.min(1e3 * 2 ** attempt, 3e4);
871
+ resolveRetryConfig = (config) => {
872
+ const retry = config.retry;
873
+ if (retry === false) return { count: 0 };
874
+ if (retry === true || retry === void 0) return { count: DEFAULT_RETRY, delay: DEFAULT_RETRY_DELAY };
875
+ if (typeof retry === "number") return { count: retry, delay: DEFAULT_RETRY_DELAY };
876
+ return {
877
+ count: retry.count ?? DEFAULT_RETRY,
878
+ delay: isFunction2(retry.delay) ? retry.delay : typeof retry.delay === "number" ? () => retry.delay : DEFAULT_RETRY_DELAY
879
+ };
880
+ };
881
+ withRetry = async (fn, retryConfig) => {
882
+ const { count, delay } = retryConfig;
883
+ let lastError;
884
+ for (let attempt = 0; attempt <= count; attempt++) {
885
+ try {
886
+ const result = await fn();
887
+ if (result?.error) {
888
+ lastError = result.error;
889
+ if (attempt < count) {
890
+ const ms = isFunction2(delay) ? delay(attempt, lastError) : delay;
891
+ await new Promise((r) => setTimeout(r, ms));
892
+ continue;
893
+ }
894
+ return result;
895
+ }
896
+ return result;
897
+ } catch (e) {
898
+ lastError = e;
899
+ if (attempt < count) {
900
+ const ms = isFunction2(delay) ? delay(attempt, e) : delay;
901
+ await new Promise((r) => setTimeout(r, ms));
902
+ continue;
903
+ }
904
+ throw e;
905
+ }
906
+ }
907
+ return { data: null, error: lastError };
908
+ };
909
+ globalListeners = { focus: /* @__PURE__ */ new Set(), online: /* @__PURE__ */ new Set() };
910
+ globalListenersAttached = false;
911
+ attachGlobalListeners = () => {
912
+ if (globalListenersAttached || typeof window === "undefined") return;
913
+ globalListenersAttached = true;
914
+ const onFocus = () => {
915
+ for (const fn of globalListeners.focus) fn();
916
+ };
917
+ const onOnline = () => {
918
+ for (const fn of globalListeners.online) fn();
919
+ };
920
+ window.addEventListener("visibilitychange", () => {
921
+ if (document.visibilityState === "visible") onFocus();
922
+ });
923
+ window.addEventListener("focus", onFocus);
924
+ window.addEventListener("online", onOnline);
925
+ };
926
+ resolveFetchConfig = (fetchProp, element) => {
927
+ const ref = element.__ref;
928
+ if (fetchProp === true) {
929
+ return { from: ref.__state || element.key, method: "select", query: true, on: "create" };
930
+ }
931
+ if (isString2(fetchProp)) {
932
+ return { from: fetchProp, method: "select", query: true, on: "create" };
933
+ }
934
+ if (isObject2(fetchProp)) {
935
+ const config = { ...fetchProp };
936
+ config.from = config.from || ref.__state || element.key;
937
+ config.method = config.method || "select";
938
+ config.on = config.on || "create";
939
+ if (config.query === void 0) config.query = true;
940
+ return config;
941
+ }
942
+ return null;
943
+ };
944
+ resolveParamsSync = (params) => {
945
+ if (!params || isFunction2(params)) return params;
946
+ return params;
947
+ };
948
+ resolveParams = (params, element) => {
949
+ if (!params) return void 0;
950
+ if (isFunction2(params)) return params(element, element.state);
951
+ const resolved = {};
952
+ for (const key in params) {
953
+ const val = params[key];
954
+ resolved[key] = isFunction2(val) ? val(element, element.state) : val;
955
+ }
956
+ return resolved;
957
+ };
958
+ initAdapterAuth = async (adapter, context) => {
959
+ if (adapter.__authInitialized) return;
960
+ adapter.__authInitialized = true;
961
+ if (!adapter.getSession) return;
962
+ const updateAuth = (user, session) => {
963
+ const root = context.state?.root;
964
+ if (root?.update) {
965
+ root.update({ auth: { user, session, loading: false } });
966
+ }
967
+ };
968
+ try {
969
+ const session = await adapter.getSession();
970
+ updateAuth(session?.user || null, session);
971
+ } catch (e) {
972
+ }
973
+ if (adapter.onAuthStateChange) {
974
+ adapter.onAuthStateChange((event, session) => {
975
+ updateAuth(session?.user || null, session);
976
+ });
977
+ }
978
+ };
979
+ resolveAdapter = async (db, context) => {
980
+ if (isFunction2(db.select)) {
981
+ if (db.auth !== false) await initAdapterAuth(db, context);
982
+ return db;
983
+ }
984
+ if (db.__resolved) {
985
+ if (db.auth !== false) await initAdapterAuth(db.__resolved, context);
986
+ return db.__resolved;
987
+ }
988
+ if (db.__resolving) return db.__resolving;
989
+ db.__resolving = resolveDb(db);
990
+ const resolved = await db.__resolving;
991
+ db.__resolved = resolved;
992
+ context.db = resolved;
993
+ delete db.__resolving;
994
+ if (db.auth !== false) await initAdapterAuth(resolved, context);
995
+ return resolved;
996
+ };
997
+ triggerCallback = (element, name, ...args) => {
998
+ const fn = isFunction2(element[name]) ? element[name] : element.props && isFunction2(element.props[name]) ? element.props[name] : null;
999
+ if (fn) fn.call(element, ...args, element, element.state, element.context);
1000
+ };
1001
+ collectFormData = (element) => {
1002
+ const data = {};
1003
+ const node = element.node;
1004
+ if (!node) return data;
1005
+ if (node.tagName === "FORM") {
1006
+ const formData = new FormData(node);
1007
+ for (const [key, value] of formData.entries()) {
1008
+ data[key] = value;
1009
+ }
1010
+ return data;
1011
+ }
1012
+ const inputs = node.querySelectorAll("input, textarea, select");
1013
+ for (let i = 0; i < inputs.length; i++) {
1014
+ const input = inputs[i];
1015
+ const name = input.name || input.getAttribute("name");
1016
+ if (!name) continue;
1017
+ if (input.type === "checkbox") {
1018
+ data[name] = input.checked;
1019
+ } else if (input.type === "file") {
1020
+ data[name] = input.files;
1021
+ } else {
1022
+ data[name] = input.value;
1023
+ }
1024
+ }
1025
+ return data;
1026
+ };
1027
+ updateElementState = (element, data, stateKey, options = {}) => {
1028
+ const stateData = stateKey ? { [stateKey]: data } : data;
1029
+ if (element.state?.update) {
1030
+ element.state.update(stateData, { preventFetch: true, ...options });
1031
+ }
1032
+ };
1033
+ setFetchStatus = (element, status) => {
1034
+ const ref = element.__ref;
1035
+ ref.__fetchStatus = status;
1036
+ ref.__fetching = status.isFetching;
1037
+ ref.__fetchError = status.error;
1038
+ };
1039
+ runFetch = async (config, element, context, opts = {}) => {
1040
+ const db = context?.db;
1041
+ if (!db) return;
1042
+ if (config.enabled === false) return;
1043
+ if (isFunction2(config.enabled) && !config.enabled(element, element.state)) return;
1044
+ const adapter = await resolveAdapter(db, context);
1045
+ if (!adapter) return;
1046
+ const ref = element.__ref;
1047
+ const {
1048
+ from,
1049
+ method,
1050
+ query,
1051
+ params: rawParams,
1052
+ cache: cacheRaw,
1053
+ transform,
1054
+ single,
1055
+ auth,
1056
+ fields,
1057
+ as: stateKey,
1058
+ limit,
1059
+ offset,
1060
+ order,
1061
+ headers,
1062
+ baseUrl,
1063
+ // Pagination
1064
+ page,
1065
+ cursor,
1066
+ getNextPageParam,
1067
+ getPreviousPageParam,
1068
+ infinite,
1069
+ // TanStack-style options
1070
+ placeholderData,
1071
+ initialData,
1072
+ select: selectTransform,
1073
+ keepPreviousData
1074
+ } = config;
1075
+ let select;
1076
+ if (query && isFunction2(element.getQuery)) {
1077
+ const q = element.getQuery(adapter.name || "paths");
1078
+ if (q) select = q.select || q.length && q.join(",") || void 0;
1079
+ }
1080
+ const params = resolveParams(rawParams, element);
1081
+ const cacheConfig = parseCacheConfig(cacheRaw);
1082
+ const retryConfig = resolveRetryConfig(config);
1083
+ const cacheKey = cacheConfig ? cacheRaw?.key || `${from}:${method}:${JSON.stringify(params || "")}${infinite ? ":infinite" : ""}${page ? ":p" + JSON.stringify(page) : ""}` : null;
1084
+ if (!ref.__fetchInitialized && cacheKey) {
1085
+ ref.__fetchInitialized = true;
1086
+ if (initialData !== void 0) {
1087
+ const initData = isFunction2(initialData) ? initialData() : initialData;
1088
+ setCacheEntry(cacheKey, initData, null);
1089
+ }
1090
+ }
1091
+ if ((method === "select" || method === "rpc") && cacheKey && cacheConfig) {
1092
+ const cached = getCacheEntry(cacheKey);
1093
+ if (cached && !cached.error) {
1094
+ const age = Date.now() - cached.time;
1095
+ const isStale = cached.stale || age > (cacheConfig.staleTime || 0);
1096
+ let data = cached.data;
1097
+ if (selectTransform) data = selectTransform(data, element, element.state);
1098
+ if (transform) data = transform(data, element, element.state);
1099
+ updateElementState(element, data, stateKey);
1100
+ if (!isStale) {
1101
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: true, error: null, status: "success", fetchStatus: "idle" });
1102
+ return;
1103
+ }
1104
+ } else if (placeholderData !== void 0) {
1105
+ const phData = isFunction2(placeholderData) ? placeholderData(element, element.state) : placeholderData;
1106
+ if (phData !== void 0) {
1107
+ updateElementState(element, phData, stateKey);
1108
+ }
1109
+ }
1110
+ }
1111
+ if (cacheKey && activeQueries.has(cacheKey) && !opts.force) {
1112
+ const existing = activeQueries.get(cacheKey);
1113
+ try {
1114
+ const result = await existing;
1115
+ if (result?.data !== void 0) {
1116
+ let finalData = result.data;
1117
+ if (selectTransform) finalData = selectTransform(finalData, element, element.state);
1118
+ if (transform) finalData = transform(finalData, element, element.state);
1119
+ updateElementState(element, finalData, stateKey);
1120
+ triggerCallback(element, "onFetchComplete", finalData);
1121
+ }
1122
+ } catch (e) {
1123
+ }
1124
+ return;
1125
+ }
1126
+ const isFirstLoad = !getCacheEntry(cacheKey)?.data;
1127
+ setFetchStatus(element, {
1128
+ isFetching: true,
1129
+ isLoading: isFirstLoad,
1130
+ isStale: false,
1131
+ isSuccess: false,
1132
+ error: null,
1133
+ status: "pending",
1134
+ fetchStatus: "fetching"
1135
+ });
1136
+ triggerCallback(element, "onFetchStart");
1137
+ const doFetch = async () => {
1138
+ if (auth !== false && adapter.getSession) {
1139
+ const session = await adapter.getSession();
1140
+ if (auth === true && !session) {
1141
+ const err = { message: "Not authenticated" };
1142
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: err, status: "error", fetchStatus: "idle" });
1143
+ triggerCallback(element, "onFetchError", err);
1144
+ return { data: null, error: err };
1145
+ }
1146
+ }
1147
+ const fn = adapter[method];
1148
+ if (!isFunction2(fn)) return { data: null, error: { message: `Method "${method}" not found on adapter` } };
1149
+ const request2 = { from, select, params, single, limit, offset, order, headers, baseUrl };
1150
+ if (page !== void 0) {
1151
+ if (isObject2(page)) {
1152
+ if (page.offset !== void 0) request2.offset = page.offset;
1153
+ if (page.limit !== void 0) request2.limit = page.limit;
1154
+ if (page.cursor !== void 0) request2.params = { ...request2.params, cursor: page.cursor };
1155
+ } else if (typeof page === "number") {
1156
+ const pageSize = config.pageSize || limit || 20;
1157
+ request2.offset = (page - 1) * pageSize;
1158
+ request2.limit = pageSize;
1159
+ }
1160
+ }
1161
+ if (cursor !== void 0) {
1162
+ request2.params = { ...request2.params, cursor };
1163
+ }
1164
+ if (method === "insert" || method === "update" || method === "upsert") {
1165
+ let data;
1166
+ if (fields === true || config.on === "submit") {
1167
+ data = collectFormData(element);
1168
+ } else if (isArray2(fields)) {
1169
+ const formData = collectFormData(element);
1170
+ data = {};
1171
+ for (const f of fields) data[f] = formData[f];
1172
+ } else if (element.state?.parse) {
1173
+ data = element.state.parse();
1174
+ } else if (isObject2(element.state)) {
1175
+ data = { ...element.state };
1176
+ }
1177
+ if (transform) data = transform(data, element, element.state);
1178
+ request2.data = data;
1179
+ }
1180
+ if (method === "rpc") {
1181
+ let rpcParams = params;
1182
+ if (config.on === "submit") {
1183
+ const formData = collectFormData(element);
1184
+ rpcParams = config.transformParams ? config.transformParams(formData, element, element.state) : formData;
1185
+ }
1186
+ request2.params = rpcParams;
1187
+ }
1188
+ if (method === "subscribe") {
1189
+ const unsubscribe = adapter.subscribe(
1190
+ { from, params, on: config.subscribeOn },
1191
+ (newData, oldData, payload) => {
1192
+ updateElementState(element, newData, stateKey);
1193
+ triggerCallback(element, "onFetchComplete", newData);
1194
+ }
1195
+ );
1196
+ ref.__unsubscribe = unsubscribe;
1197
+ return { data: null, error: null, subscribed: true };
1198
+ }
1199
+ return fn(request2);
1200
+ };
1201
+ const fetchPromise = withRetry(doFetch, retryConfig);
1202
+ if (cacheKey) activeQueries.set(cacheKey, fetchPromise);
1203
+ try {
1204
+ const result = await fetchPromise;
1205
+ if (result?.subscribed) return;
1206
+ const { data, error: error2 } = result || {};
1207
+ if (error2) {
1208
+ if (cacheKey) setCacheEntry(cacheKey, null, error2);
1209
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: error2, status: "error", fetchStatus: "idle" });
1210
+ triggerCallback(element, "onFetchError", error2);
1211
+ return;
1212
+ }
1213
+ if (data !== void 0) {
1214
+ if ((method === "select" || method === "rpc") && cacheKey) {
1215
+ const entry = setCacheEntry(cacheKey, data, null);
1216
+ entry.gcTime = cacheConfig?.gcTime || 3e5;
1217
+ }
1218
+ let finalData = data;
1219
+ if (infinite && isArray2(data)) {
1220
+ if (!ref.__pages) ref.__pages = [];
1221
+ if (opts.direction === "previous") {
1222
+ ref.__pages.unshift(data);
1223
+ } else {
1224
+ ref.__pages.push(data);
1225
+ }
1226
+ finalData = ref.__pages.flat();
1227
+ if (getNextPageParam) {
1228
+ ref.__nextPageParam = getNextPageParam(data, ref.__pages);
1229
+ ref.__hasNextPage = ref.__nextPageParam != null;
1230
+ }
1231
+ if (getPreviousPageParam) {
1232
+ ref.__prevPageParam = getPreviousPageParam(data, ref.__pages);
1233
+ ref.__hasPreviousPage = ref.__prevPageParam != null;
1234
+ }
1235
+ }
1236
+ if (selectTransform) finalData = selectTransform(finalData, element, element.state);
1237
+ if (transform) finalData = transform(finalData, element, element.state);
1238
+ if (!keepPreviousData || finalData !== void 0) {
1239
+ updateElementState(element, finalData, stateKey);
1240
+ }
1241
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: true, error: null, status: "success", fetchStatus: "idle" });
1242
+ triggerCallback(element, "onFetchComplete", finalData);
1243
+ }
1244
+ } catch (e) {
1245
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: e, status: "error", fetchStatus: "idle" });
1246
+ triggerCallback(element, "onFetchError", e);
1247
+ } finally {
1248
+ if (cacheKey) activeQueries.delete(cacheKey);
1249
+ }
1250
+ };
1251
+ bindEvent = (config, element, context) => {
1252
+ const on = config.on;
1253
+ const ref = element.__ref;
1254
+ if (!ref.__fetchListeners) ref.__fetchListeners = [];
1255
+ const runner = config.__runner || runFetch;
1256
+ if (on === "submit") {
1257
+ const handler = (e) => {
1258
+ e.preventDefault();
1259
+ runner(config, element, context);
1260
+ };
1261
+ const node = element.node;
1262
+ if (node) {
1263
+ node.addEventListener("submit", handler);
1264
+ ref.__fetchListeners.push(() => node.removeEventListener("submit", handler));
1265
+ }
1266
+ } else if (on === "click") {
1267
+ const handler = () => runner(config, element, context);
1268
+ const node = element.node;
1269
+ if (node) {
1270
+ node.addEventListener("click", handler);
1271
+ ref.__fetchListeners.push(() => node.removeEventListener("click", handler));
1272
+ }
1273
+ } else if (on === "stateChange") {
1274
+ ref.__fetchOnStateChange = () => runner(config, element, context);
1275
+ }
1276
+ };
1277
+ bindAutoRefetch = (config, element, context) => {
1278
+ const ref = element.__ref;
1279
+ if (!ref.__fetchCleanups) ref.__fetchCleanups = [];
1280
+ attachGlobalListeners();
1281
+ const interval = config.refetchInterval;
1282
+ if (interval) {
1283
+ const ms = typeof interval === "number" ? interval : parseDuration(interval);
1284
+ if (ms > 0) {
1285
+ const timer = setInterval(() => {
1286
+ if (config.refetchIntervalInBackground || typeof document === "undefined" || document.visibilityState === "visible") {
1287
+ runFetch(config, element, context, { force: true });
1288
+ }
1289
+ }, ms);
1290
+ ref.__fetchCleanups.push(() => clearInterval(timer));
1291
+ }
1292
+ }
1293
+ if (config.refetchOnWindowFocus !== false) {
1294
+ const onFocus = () => {
1295
+ const cacheKey = buildCacheKey(config);
1296
+ const entry = getCacheEntry(cacheKey);
1297
+ const cacheConfig = parseCacheConfig(config.cache);
1298
+ if (!entry || entry.stale || Date.now() - entry.time > (cacheConfig?.staleTime || 0)) {
1299
+ runFetch(config, element, context, { force: true });
1300
+ }
1301
+ };
1302
+ globalListeners.focus.add(onFocus);
1303
+ ref.__fetchCleanups.push(() => globalListeners.focus.delete(onFocus));
1304
+ }
1305
+ if (config.refetchOnReconnect !== false) {
1306
+ const onOnline = () => runFetch(config, element, context, { force: true });
1307
+ globalListeners.online.add(onOnline);
1308
+ ref.__fetchCleanups.push(() => globalListeners.online.delete(onOnline));
1309
+ }
1310
+ };
1311
+ applyOptimisticUpdate = (element, config, mutationData) => {
1312
+ if (!config.optimistic) return null;
1313
+ const ref = element.__ref;
1314
+ const stateKey = config.as;
1315
+ const snapshot2 = element.state?.parse ? element.state.parse() : isObject2(element.state) ? { ...element.state } : element.state;
1316
+ ref.__optimisticSnapshot = snapshot2;
1317
+ const optimisticData = isFunction2(config.optimistic) ? config.optimistic(mutationData, snapshot2, element) : config.optimistic;
1318
+ if (optimisticData !== void 0) {
1319
+ updateElementState(element, optimisticData, stateKey);
1320
+ }
1321
+ return snapshot2;
1322
+ };
1323
+ rollbackOptimistic = (element, config) => {
1324
+ const ref = element.__ref;
1325
+ const snapshot2 = ref.__optimisticSnapshot;
1326
+ if (snapshot2 !== void 0) {
1327
+ updateElementState(element, snapshot2, config.as);
1328
+ delete ref.__optimisticSnapshot;
1329
+ }
1330
+ };
1331
+ runMutation = async (config, element, context) => {
1332
+ const db = context?.db;
1333
+ if (!db) return;
1334
+ const adapter = await resolveAdapter(db, context);
1335
+ if (!adapter) return;
1336
+ const ref = element.__ref;
1337
+ const { method, from, fields, transform, as: stateKey, on: trigger, auth, headers, baseUrl, invalidates, optimistic, onMutate, onSuccess, onError, onSettled } = config;
1338
+ let mutationData;
1339
+ if (fields === true || trigger === "submit") {
1340
+ mutationData = collectFormData(element);
1341
+ } else if (isArray2(fields)) {
1342
+ const formData = collectFormData(element);
1343
+ mutationData = {};
1344
+ for (const f of fields) mutationData[f] = formData[f];
1345
+ } else if (element.state?.parse) {
1346
+ mutationData = element.state.parse();
1347
+ } else if (isObject2(element.state)) {
1348
+ mutationData = { ...element.state };
1349
+ }
1350
+ if (transform) mutationData = transform(mutationData, element, element.state);
1351
+ if (isFunction2(onMutate)) onMutate(mutationData, element, element.state);
1352
+ const snapshot2 = optimistic ? applyOptimisticUpdate(element, config, mutationData) : null;
1353
+ ref.__fetching = true;
1354
+ setFetchStatus(element, { isFetching: true, isLoading: false, isStale: false, isSuccess: false, error: null, status: "pending", fetchStatus: "fetching" });
1355
+ triggerCallback(element, "onFetchStart");
1356
+ try {
1357
+ if (auth !== false && adapter.getSession) {
1358
+ const session = await adapter.getSession();
1359
+ if (auth === true && !session) {
1360
+ if (snapshot2 !== void 0) rollbackOptimistic(element, config);
1361
+ const err = { message: "Not authenticated" };
1362
+ triggerCallback(element, "onFetchError", err);
1363
+ return;
1364
+ }
1365
+ }
1366
+ const fn = adapter[method];
1367
+ if (!isFunction2(fn)) return;
1368
+ const request2 = { from, data: mutationData, headers, baseUrl };
1369
+ if (config.params) request2.params = resolveParams(config.params, element);
1370
+ const retryConfig = resolveRetryConfig(config);
1371
+ const result = await withRetry(() => fn(request2), retryConfig);
1372
+ const { data, error: error2 } = result || {};
1373
+ if (error2) {
1374
+ if (snapshot2 !== void 0) rollbackOptimistic(element, config);
1375
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: error2, status: "error", fetchStatus: "idle" });
1376
+ triggerCallback(element, "onFetchError", error2);
1377
+ if (isFunction2(onError)) onError(error2, mutationData, element);
1378
+ if (isFunction2(onSettled)) onSettled(null, error2, mutationData, element);
1379
+ return;
1380
+ }
1381
+ delete ref.__optimisticSnapshot;
1382
+ if (data !== void 0) {
1383
+ const finalData = stateKey ? { [stateKey]: data } : data;
1384
+ if (element.state?.update) element.state.update(finalData, { preventFetch: true });
1385
+ }
1386
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: true, error: null, status: "success", fetchStatus: "idle" });
1387
+ triggerCallback(element, "onFetchComplete", data);
1388
+ if (isFunction2(onSuccess)) onSuccess(data, mutationData, element);
1389
+ if (isFunction2(onSettled)) onSettled(data, null, mutationData, element);
1390
+ if (invalidates) {
1391
+ const keys2 = isArray2(invalidates) ? invalidates : [invalidates];
1392
+ for (const k of keys2) {
1393
+ if (k === true || k === "*") {
1394
+ for (const [ck] of cacheStore) {
1395
+ if (ck.startsWith(from + ":")) invalidateCache(ck);
1396
+ }
1397
+ } else {
1398
+ invalidateCache(k);
1399
+ }
1400
+ }
1401
+ }
1402
+ } catch (e) {
1403
+ if (snapshot2 !== void 0) rollbackOptimistic(element, config);
1404
+ setFetchStatus(element, { isFetching: false, isLoading: false, isStale: false, isSuccess: false, error: e, status: "error", fetchStatus: "idle" });
1405
+ triggerCallback(element, "onFetchError", e);
1406
+ if (isFunction2(onError)) onError(e, mutationData, element);
1407
+ if (isFunction2(onSettled)) onSettled(null, e, mutationData, element);
1408
+ } finally {
1409
+ ref.__fetching = false;
1410
+ }
1411
+ };
1412
+ executeFetch = (param, element, state, context) => {
1413
+ if (!param) return;
1414
+ const db = context?.db;
1415
+ if (!db) return;
1416
+ const fetchProp = exec2(param, element);
1417
+ if (!fetchProp) return;
1418
+ const configs = isArray2(fetchProp) ? fetchProp.map((c) => resolveFetchConfig(exec2(c, element), element)).filter(Boolean) : [resolveFetchConfig(fetchProp, element)].filter(Boolean);
1419
+ for (const config of configs) {
1420
+ const isMutation = config.method === "insert" || config.method === "update" || config.method === "upsert" || config.method === "delete";
1421
+ const runner = isMutation ? runMutation : runFetch;
1422
+ if (config.on === "create") {
1423
+ runner(config, element, context);
1424
+ } else {
1425
+ Promise.resolve().then(() => {
1426
+ bindEvent({ ...config, __runner: runner }, element, context);
1427
+ });
1428
+ }
1429
+ if (!isMutation && config.on === "create") {
1430
+ if (config.refetchInterval || config.refetchOnWindowFocus !== false || config.refetchOnReconnect !== false) {
1431
+ bindAutoRefetch(config, element, context);
1432
+ }
1433
+ }
1434
+ }
1435
+ const ref = element.__ref;
1436
+ ref.refetch = (opts) => {
1437
+ for (const config of configs) {
1438
+ runFetch(config, element, context, { force: true, ...opts });
1439
+ }
1440
+ };
1441
+ ref.fetchNextPage = () => {
1442
+ const config = configs[0];
1443
+ if (!config || !config.infinite) return;
1444
+ const nextParam = ref.__nextPageParam;
1445
+ if (nextParam == null) return;
1446
+ const nextConfig = { ...config, cursor: nextParam };
1447
+ runFetch(nextConfig, element, context, { direction: "next", force: true });
1448
+ };
1449
+ ref.fetchPreviousPage = () => {
1450
+ const config = configs[0];
1451
+ if (!config || !config.infinite) return;
1452
+ const prevParam = ref.__prevPageParam;
1453
+ if (prevParam == null) return;
1454
+ const prevConfig = { ...config, cursor: prevParam };
1455
+ runFetch(prevConfig, element, context, { direction: "previous", force: true });
1456
+ };
1457
+ };
1458
+ queryClient = {
1459
+ invalidateQueries: (keyOrPattern) => {
1460
+ if (!keyOrPattern) {
1461
+ invalidateCache();
1462
+ return;
1463
+ }
1464
+ if (isString2(keyOrPattern)) {
1465
+ for (const [key] of cacheStore) {
1466
+ if (key.startsWith(keyOrPattern) || key.includes(keyOrPattern)) {
1467
+ invalidateCache(key);
1468
+ }
1469
+ }
1470
+ } else if (isArray2(keyOrPattern)) {
1471
+ const pattern = keyOrPattern.join(":");
1472
+ for (const [key] of cacheStore) {
1473
+ if (key.includes(pattern)) invalidateCache(key);
1474
+ }
1475
+ }
1476
+ },
1477
+ removeQueries: (keyOrPattern) => {
1478
+ if (!keyOrPattern) {
1479
+ removeCache();
1480
+ return;
1481
+ }
1482
+ if (isString2(keyOrPattern)) {
1483
+ for (const [key] of cacheStore) {
1484
+ if (key.startsWith(keyOrPattern) || key.includes(keyOrPattern)) {
1485
+ removeCache(key);
1486
+ }
1487
+ }
1488
+ }
1489
+ },
1490
+ getQueryData: (key) => {
1491
+ const entry = getCacheEntry(key);
1492
+ return entry?.data ?? void 0;
1493
+ },
1494
+ setQueryData: (key, updater) => {
1495
+ const existing = getCacheEntry(key);
1496
+ const data = isFunction2(updater) ? updater(existing?.data) : updater;
1497
+ setCacheEntry(key, data, null);
1498
+ },
1499
+ prefetchQuery: async (config, context) => {
1500
+ const db = context?.db;
1501
+ if (!db) return;
1502
+ const adapter = await resolveAdapter(db, context);
1503
+ if (!adapter) return;
1504
+ const cacheKey = config.cache?.key || `${config.from}:${config.method || "select"}:${JSON.stringify(config.params || "")}`;
1505
+ const fn = adapter[config.method || "select"];
1506
+ if (!isFunction2(fn)) return;
1507
+ const result = await fn({
1508
+ from: config.from,
1509
+ params: config.params,
1510
+ limit: config.limit,
1511
+ offset: config.offset,
1512
+ order: config.order,
1513
+ single: config.single
1514
+ });
1515
+ if (result?.data !== void 0 && !result?.error) {
1516
+ const entry = setCacheEntry(cacheKey, result.data, null);
1517
+ entry.gcTime = parseCacheConfig(config.cache)?.gcTime || 3e5;
1518
+ }
1519
+ return result;
1520
+ },
1521
+ getCache: () => cacheStore,
1522
+ clear: () => removeCache()
1523
+ };
1524
+ fetch_default = executeFetch;
1525
+ }
1526
+ });
1527
+
21
1528
  // index.js
22
1529
  var index_exports = {};
23
1530
  __export(index_exports, {
@@ -116,6 +1623,7 @@ var DomqlUtils = (() => {
116
1623
  getChildren: () => getChildren,
117
1624
  getContext: () => getContext,
118
1625
  getCookie: () => getCookie,
1626
+ getDB: () => getDB,
119
1627
  getExtendsInElement: () => getExtendsInElement,
120
1628
  getExtendsStack: () => getExtendsStack,
121
1629
  getExtendsStackRegistry: () => getExtendsStackRegistry,
@@ -126,6 +1634,7 @@ var DomqlUtils = (() => {
126
1634
  getNev: () => getNev,
127
1635
  getParentStateInKey: () => getParentStateInKey,
128
1636
  getPath: () => getPath,
1637
+ getQuery: () => getQuery,
129
1638
  getRef: () => getRef,
130
1639
  getRoot: () => getRoot,
131
1640
  getRootContext: () => getRootContext,
@@ -584,6 +2093,7 @@ var DomqlUtils = (() => {
584
2093
  "node",
585
2094
  "variables",
586
2095
  "on",
2096
+ "fetch",
587
2097
  "component",
588
2098
  "context"
589
2099
  ]);
@@ -682,6 +2192,8 @@ var DomqlUtils = (() => {
682
2192
  "getRootData",
683
2193
  "getRootContext",
684
2194
  "getContext",
2195
+ "getQuery",
2196
+ "getDB",
685
2197
  "getChildren"
686
2198
  ]);
687
2199
  var METHODS_EXL = /* @__PURE__ */ new Set([
@@ -709,7 +2221,9 @@ var DomqlUtils = (() => {
709
2221
  "create",
710
2222
  "complete",
711
2223
  "frame",
712
- "update"
2224
+ "update",
2225
+ "fetchError",
2226
+ "fetchComplete"
713
2227
  ]);
714
2228
 
715
2229
  // object.js
@@ -2345,10 +3859,7 @@ var DomqlUtils = (() => {
2345
3859
  var checkForStateTypes = (element) => {
2346
3860
  const { state: orig, props, __ref: ref } = element;
2347
3861
  const state = props?.state || orig;
2348
- if (isFunction(state)) {
2349
- ref.__state = state;
2350
- return exec(state, element);
2351
- } else if (is(state)("string", "number")) {
3862
+ if (is(state)("string", "number")) {
2352
3863
  ref.__state = state;
2353
3864
  return { value: state };
2354
3865
  } else if (state === true) {
@@ -2451,7 +3962,7 @@ var DomqlUtils = (() => {
2451
3962
  };
2452
3963
  var applyDependentState = (element, state) => {
2453
3964
  const { __element } = state;
2454
- const origState = exec(__element?.state, element);
3965
+ const origState = __element?.state;
2455
3966
  if (!origState) return;
2456
3967
  const dependentState = deepClone(origState, STATE_METHODS);
2457
3968
  const newDepends = { [element.key]: dependentState };
@@ -2569,6 +4080,10 @@ var DomqlUtils = (() => {
2569
4080
  }
2570
4081
  };
2571
4082
 
4083
+ // cache.js
4084
+ var cache = {};
4085
+ var OPTIONS = {};
4086
+
2572
4087
  // methods.js
2573
4088
  var ENV5 = process.env.NODE_ENV;
2574
4089
  function spotByPath(path) {
@@ -2614,8 +4129,8 @@ var DomqlUtils = (() => {
2614
4129
  const childElem = el[v];
2615
4130
  if (v === param) return childElem;
2616
4131
  else if (isFunction(param)) {
2617
- const exec2 = param(childElem, childElem.state, childElem.context);
2618
- if (childElem.state && exec2) {
4132
+ const exec3 = param(childElem, childElem.state, childElem.context);
4133
+ if (childElem.state && exec3) {
2619
4134
  return childElem;
2620
4135
  }
2621
4136
  }
@@ -2633,8 +4148,8 @@ var DomqlUtils = (() => {
2633
4148
  const childElem = el[v];
2634
4149
  if (v === param) results.push(childElem);
2635
4150
  else if (isFunction(param)) {
2636
- const exec2 = param(childElem, childElem.state, childElem.context);
2637
- if (childElem.state && exec2) results.push(childElem);
4151
+ const exec3 = param(childElem, childElem.state, childElem.context);
4152
+ if (childElem.state && exec3) results.push(childElem);
2638
4153
  }
2639
4154
  childElem?.lookdownAll?.(param, results);
2640
4155
  }
@@ -2883,14 +4398,223 @@ var DomqlUtils = (() => {
2883
4398
  if (context?.strictMode) throw err;
2884
4399
  }
2885
4400
  }
4401
+ async function getDB() {
4402
+ const element = this;
4403
+ const db = element.context?.db;
4404
+ if (!db) return null;
4405
+ if (typeof db.select === "function") {
4406
+ if (!db.__authInitialized && db.getSession) {
4407
+ const { initAdapterAuth: initAdapterAuth2 } = await Promise.resolve().then(() => (init_fetch(), fetch_exports));
4408
+ await initAdapterAuth2(db, element.context);
4409
+ }
4410
+ return db;
4411
+ }
4412
+ if (db.__resolved) {
4413
+ if (!db.__resolved.__authInitialized && db.__resolved.getSession) {
4414
+ const { initAdapterAuth: initAdapterAuth2 } = await Promise.resolve().then(() => (init_fetch(), fetch_exports));
4415
+ await initAdapterAuth2(db.__resolved, element.context);
4416
+ }
4417
+ return db.__resolved;
4418
+ }
4419
+ if (db.__resolving) return db.__resolving;
4420
+ const resolvePromise = Promise.resolve().then(() => (init_fetch(), fetch_exports)).then(({ resolveDb: resolveDb2 }) => resolveDb2(db));
4421
+ db.__resolving = resolvePromise;
4422
+ const resolved = await resolvePromise;
4423
+ db.__resolved = resolved;
4424
+ element.context.db = resolved;
4425
+ delete db.__resolving;
4426
+ if (resolved.getSession) {
4427
+ const { initAdapterAuth: initAdapterAuth2 } = await Promise.resolve().then(() => (init_fetch(), fetch_exports));
4428
+ await initAdapterAuth2(resolved, element.context);
4429
+ }
4430
+ return resolved;
4431
+ }
4432
+ function getQuery(format) {
4433
+ const element = this;
4434
+ const useStateQuery = format || OPTIONS.useStateQuery || element.context?.useStateQuery;
4435
+ if (!useStateQuery) return null;
4436
+ const query = {};
4437
+ buildQueryFromElement(element, query);
4438
+ if (useStateQuery === true) return query;
4439
+ const formatter = QUERY_FORMATTERS[useStateQuery];
4440
+ return formatter ? formatter(query) : query;
4441
+ }
4442
+ var buildQueryFromElement = (element, query) => {
4443
+ const ref = element.__ref;
4444
+ if (!ref) return;
4445
+ const stateKey = ref.__state;
4446
+ if (stateKey && typeof stateKey === "string") {
4447
+ setQueryPath(query, stateKey);
4448
+ }
4449
+ const children = ref.__children;
4450
+ if (children) {
4451
+ for (let i = 0; i < children.length; i++) {
4452
+ const child = element[children[i]];
4453
+ if (child && child.__ref) {
4454
+ buildQueryFromElement(child, query);
4455
+ }
4456
+ }
4457
+ }
4458
+ const contentKey = ref.contentElementKey || "content";
4459
+ const content = element[contentKey];
4460
+ if (content && content.__ref) {
4461
+ buildQueryFromElement(content, query);
4462
+ }
4463
+ };
4464
+ var setQueryPath = (query, path) => {
4465
+ const clean = path.replaceAll("../", "").replaceAll("~/", "");
4466
+ const parts = clean.split("/");
4467
+ let current = query;
4468
+ for (let i = 0; i < parts.length; i++) {
4469
+ const part = parts[i];
4470
+ if (i === parts.length - 1) {
4471
+ if (!current[part]) current[part] = true;
4472
+ } else {
4473
+ if (current[part] === true) current[part] = {};
4474
+ if (!current[part]) current[part] = {};
4475
+ current = current[part];
4476
+ }
4477
+ }
4478
+ };
4479
+ var queryToGraphQL = (query, indent = 0) => {
4480
+ const pad = " ".repeat(indent);
4481
+ const entries = Object.entries(query);
4482
+ if (!entries.length) return "";
4483
+ const fields = entries.map(([key, value]) => {
4484
+ if (value === true) return `${pad}${key}`;
4485
+ return `${pad}${key} {
4486
+ ${queryToGraphQL(value, indent + 1)}
4487
+ ${pad}}`;
4488
+ });
4489
+ return fields.join("\n");
4490
+ };
4491
+ var formatGraphQL = (query) => {
4492
+ return `{
4493
+ ${queryToGraphQL(query, 1)}
4494
+ }`;
4495
+ };
4496
+ var formatJsonApi = (query) => {
4497
+ const result = { fields: {}, include: [] };
4498
+ const walk = (obj, prefix) => {
4499
+ const fields = [];
4500
+ for (const key in obj) {
4501
+ if (obj[key] === true) {
4502
+ fields.push(key);
4503
+ } else {
4504
+ const nested = prefix ? `${prefix}.${key}` : key;
4505
+ result.include.push(nested);
4506
+ walk(obj[key], nested);
4507
+ }
4508
+ }
4509
+ if (fields.length) {
4510
+ result.fields[prefix || "_root"] = fields;
4511
+ }
4512
+ };
4513
+ walk(query, "");
4514
+ return result;
4515
+ };
4516
+ var formatOData = (query) => {
4517
+ const build = (obj) => {
4518
+ const select2 = [];
4519
+ const expand2 = [];
4520
+ for (const key in obj) {
4521
+ if (obj[key] === true) {
4522
+ select2.push(key);
4523
+ } else {
4524
+ const nested = build(obj[key]);
4525
+ const parts2 = [];
4526
+ if (nested.select) parts2.push(`$select=${nested.select}`);
4527
+ if (nested.expand) parts2.push(`$expand=${nested.expand}`);
4528
+ expand2.push(parts2.length ? `${key}(${parts2.join(";")})` : key);
4529
+ }
4530
+ }
4531
+ return {
4532
+ select: select2.length ? select2.join(",") : "",
4533
+ expand: expand2.length ? expand2.join(",") : ""
4534
+ };
4535
+ };
4536
+ const { select, expand } = build(query);
4537
+ const parts = [];
4538
+ if (select) parts.push(`$select=${select}`);
4539
+ if (expand) parts.push(`$expand=${expand}`);
4540
+ return parts.join("&");
4541
+ };
4542
+ var formatSQL = (query, options) => {
4543
+ const columns = [];
4544
+ const joins = [];
4545
+ const tables = /* @__PURE__ */ new Set();
4546
+ const walk = (obj, table, parentTable) => {
4547
+ tables.add(table);
4548
+ if (parentTable) {
4549
+ joins.push(
4550
+ `LEFT JOIN ${table} ON ${table}.${parentTable}_id = ${parentTable}.id`
4551
+ );
4552
+ }
4553
+ for (const key in obj) {
4554
+ if (obj[key] === true) {
4555
+ columns.push(`${table}.${key}`);
4556
+ } else {
4557
+ walk(obj[key], key, table);
4558
+ }
4559
+ }
4560
+ };
4561
+ const roots = Object.keys(query);
4562
+ if (roots.length === 1 && query[roots[0]] !== true) {
4563
+ walk(query[roots[0]], roots[0], null);
4564
+ } else {
4565
+ walk(query, "_root", null);
4566
+ }
4567
+ const from = [...tables][0] || "_root";
4568
+ const select = columns.length ? columns.join(", ") : "*";
4569
+ const joinStr = joins.length ? "\n" + joins.join("\n") : "";
4570
+ return `SELECT ${select}
4571
+ FROM ${from}${joinStr}`;
4572
+ };
4573
+ var formatPaths = (query) => {
4574
+ const paths = [];
4575
+ const walk = (obj, prefix) => {
4576
+ for (const key in obj) {
4577
+ const path = prefix ? `${prefix}/${key}` : key;
4578
+ if (obj[key] === true) {
4579
+ paths.push(path);
4580
+ } else {
4581
+ walk(obj[key], path);
4582
+ }
4583
+ }
4584
+ };
4585
+ walk(query, "");
4586
+ return paths;
4587
+ };
4588
+ var formatSupabase = (query) => {
4589
+ const build = (obj) => {
4590
+ const parts = [];
4591
+ for (const key in obj) {
4592
+ if (obj[key] === true) {
4593
+ parts.push(key);
4594
+ } else {
4595
+ parts.push(`${key}(${build(obj[key])})`);
4596
+ }
4597
+ }
4598
+ return parts.join(", ");
4599
+ };
4600
+ const roots = Object.keys(query);
4601
+ if (roots.length === 1 && query[roots[0]] !== true) {
4602
+ return { from: roots[0], select: build(query[roots[0]]) };
4603
+ }
4604
+ return { from: null, select: build(query) };
4605
+ };
4606
+ var QUERY_FORMATTERS = {
4607
+ graphql: formatGraphQL,
4608
+ "json-api": formatJsonApi,
4609
+ odata: formatOData,
4610
+ sql: formatSQL,
4611
+ supabase: formatSupabase,
4612
+ paths: formatPaths
4613
+ };
2886
4614
  function isMethod(param, element) {
2887
4615
  return Boolean(METHODS.has(param) || element?.context?.methods?.[param]);
2888
4616
  }
2889
4617
 
2890
- // cache.js
2891
- var cache = {};
2892
- var OPTIONS = {};
2893
-
2894
4618
  // update.js
2895
4619
  var snapshot = {
2896
4620
  snapshotId: createSnapshotId