@burojs/hasura 0.2.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.cjs ADDED
@@ -0,0 +1,854 @@
1
+ 'use strict';
2
+
3
+ var core = require('@burojs/core');
4
+ var graphqlWs = require('graphql-ws');
5
+
6
+ // src/data-provider.ts
7
+
8
+ // src/endpoint.ts
9
+ var DEFAULT_HASURA_ENDPOINT = "/gql/v1/graphql";
10
+ function hasuraWsUrl(endpoint) {
11
+ if (typeof window === "undefined") return endpoint;
12
+ const url = new URL(endpoint, window.location.origin);
13
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
14
+ return url.toString();
15
+ }
16
+ function listSubscription(mapping) {
17
+ const where = mapping.fixedFilter;
18
+ return {
19
+ query: where ? `subscription Live_${mapping.table}_list($where: ${mapping.table}_bool_exp) {
20
+ ${mapping.table}_aggregate(where: $where) { aggregate { count max { updated_at } } }
21
+ }` : `subscription Live_${mapping.table}_list {
22
+ ${mapping.table}_aggregate { aggregate { count max { updated_at } } }
23
+ }`,
24
+ ...where === void 0 ? {} : { variables: { where } }
25
+ };
26
+ }
27
+ function oneSubscription(mapping, id) {
28
+ const pkField = mapping.pkField ?? "id";
29
+ const pkType = mapping.pkType ?? "bigint";
30
+ const root = mapping.byPkRoot === false ? null : mapping.byPkRoot ?? `${mapping.table}_by_pk`;
31
+ if (root === null) return null;
32
+ return {
33
+ query: `subscription Live_${mapping.table}_one($id: ${pkType}!) {
34
+ ${root}(${pkField}: $id) { ${pkField} updated_at }
35
+ }`,
36
+ variables: { id }
37
+ };
38
+ }
39
+ function createHasuraLiveProvider(config) {
40
+ const listeners = /* @__PURE__ */ new Set();
41
+ const endpoint = config.endpoint ?? DEFAULT_HASURA_ENDPOINT;
42
+ const role = config.role ?? null;
43
+ let client;
44
+ const status = (value) => {
45
+ for (const listener of listeners) listener(value);
46
+ };
47
+ function getClient() {
48
+ if (client !== void 0) return client;
49
+ const options = {
50
+ url: hasuraWsUrl(endpoint),
51
+ lazy: true,
52
+ keepAlive: 1e4,
53
+ retryAttempts: Number.POSITIVE_INFINITY,
54
+ shouldRetry: () => true,
55
+ connectionParams: async () => {
56
+ const token = await config.getToken();
57
+ return {
58
+ headers: {
59
+ ...token ? { Authorization: `Bearer ${token}` } : {},
60
+ ...role ? { "X-Hasura-Role": role } : {}
61
+ }
62
+ };
63
+ },
64
+ on: {
65
+ connecting: () => status("connecting"),
66
+ connected: () => status("connected"),
67
+ closed: () => status("degraded")
68
+ }
69
+ };
70
+ client = config.clientFactory?.(options) ?? graphqlWs.createClient(options);
71
+ return client;
72
+ }
73
+ return {
74
+ async open(descriptor, openContext) {
75
+ if (openContext.signal.aborted) return null;
76
+ const mapping = config.resources[descriptor.resource];
77
+ if (mapping?.live !== true) return null;
78
+ const payload = descriptor.kind === "list" ? listSubscription(mapping) : descriptor.kind === "one" ? oneSubscription(mapping, descriptor.id) : null;
79
+ if (payload === null) return null;
80
+ return {
81
+ kind: "invalidate",
82
+ initial: "query",
83
+ subscribe(observer, subscribeContext) {
84
+ if (openContext.signal.aborted || subscribeContext.signal.aborted) return () => void 0;
85
+ let primed = false;
86
+ let closed = false;
87
+ let upstream = void 0;
88
+ const close = () => {
89
+ if (closed) return;
90
+ closed = true;
91
+ listeners.delete(onStatus);
92
+ openContext.signal.removeEventListener("abort", close);
93
+ subscribeContext.signal.removeEventListener("abort", close);
94
+ upstream?.();
95
+ };
96
+ const onStatus = (value) => {
97
+ if (!closed) observer.status(value);
98
+ };
99
+ const sink = {
100
+ next: () => {
101
+ if (closed) return;
102
+ if (!primed) {
103
+ primed = true;
104
+ return;
105
+ }
106
+ observer.next(void 0);
107
+ },
108
+ error: (error) => {
109
+ if (closed) return;
110
+ observer.error(core.normalizeDataError(error));
111
+ close();
112
+ },
113
+ complete: () => {
114
+ if (!closed) observer.status("degraded");
115
+ }
116
+ };
117
+ listeners.add(onStatus);
118
+ openContext.signal.addEventListener("abort", close, { once: true });
119
+ subscribeContext.signal.addEventListener("abort", close, { once: true });
120
+ upstream = getClient().subscribe(payload, sink);
121
+ if (closed) upstream();
122
+ if (openContext.signal.aborted || subscribeContext.signal.aborted) close();
123
+ return Promise.resolve(close);
124
+ }
125
+ };
126
+ }
127
+ };
128
+ }
129
+
130
+ // src/data-provider.ts
131
+ function setNestedPath(obj, path, value) {
132
+ const parts = path.split(".");
133
+ const leaf = parts.pop();
134
+ if (leaf === void 0) return;
135
+ let cur = obj;
136
+ for (const p of parts) {
137
+ const next = cur[p];
138
+ if (typeof next !== "object" || next === null) cur[p] = {};
139
+ cur = cur[p];
140
+ }
141
+ cur[leaf] = value;
142
+ }
143
+ function getNestedPath(obj, path) {
144
+ let cur = obj;
145
+ for (const p of path.split(".")) {
146
+ if (cur == null || typeof cur !== "object") return void 0;
147
+ cur = cur[p];
148
+ }
149
+ return cur;
150
+ }
151
+ function partitionDataBody(values, cfg) {
152
+ const keySet = new Set(cfg.keys);
153
+ const dataBody = {};
154
+ const rest = {};
155
+ let hasDataBody = false;
156
+ for (const [key, value] of Object.entries(values)) {
157
+ if (key === cfg.relationship) continue;
158
+ if (keySet.has(key)) {
159
+ if (value !== void 0) {
160
+ dataBody[key] = value;
161
+ hasDataBody = true;
162
+ }
163
+ } else {
164
+ rest[key] = value;
165
+ }
166
+ }
167
+ return { dataBody, rest, hasDataBody };
168
+ }
169
+ function partitionJsonbSpill(values, spill, baseColumns) {
170
+ const baseSet = new Set(baseColumns);
171
+ const metaSet = new Set(spill.metaKeys);
172
+ const nestedKeys = spill.nestedKeys ?? {};
173
+ const base = {};
174
+ const headExplicit = {};
175
+ const metaExplicit = {};
176
+ const headSpill = {};
177
+ const metaSpill = {};
178
+ const nestedSpill = [];
179
+ for (const [key, value] of Object.entries(values)) {
180
+ if (value === void 0) continue;
181
+ const nestedPath = nestedKeys[key];
182
+ if (key === spill.column) {
183
+ if (value && typeof value === "object")
184
+ Object.assign(headExplicit, value);
185
+ } else if (key === spill.metaColumn) {
186
+ if (value && typeof value === "object")
187
+ Object.assign(metaExplicit, value);
188
+ } else if (metaSet.has(key)) {
189
+ metaSpill[key] = value;
190
+ } else if (nestedPath) {
191
+ nestedSpill.push([nestedPath, value]);
192
+ } else if (baseSet.has(key)) {
193
+ base[key] = value;
194
+ } else {
195
+ headSpill[key] = value;
196
+ }
197
+ }
198
+ const head = { ...headExplicit, ...headSpill };
199
+ for (const [path, value] of nestedSpill) setNestedPath(head, path, value);
200
+ const meta = { ...metaExplicit, ...metaSpill };
201
+ const out = { ...base };
202
+ if (Object.keys(head).length > 0) out[spill.column] = head;
203
+ if (Object.keys(meta).length > 0) out[spill.metaColumn] = meta;
204
+ return out;
205
+ }
206
+ function flattenJsonbSpill(item, spill) {
207
+ if (!item || typeof item !== "object") return item;
208
+ const rec = item;
209
+ const headObj = rec[spill.column];
210
+ const metaObj = rec[spill.metaColumn];
211
+ const out = {
212
+ ...headObj && typeof headObj === "object" ? headObj : {},
213
+ ...metaObj && typeof metaObj === "object" ? metaObj : {},
214
+ ...rec
215
+ };
216
+ if (spill.nestedKeys && headObj && typeof headObj === "object") {
217
+ for (const [flatKey, path] of Object.entries(spill.nestedKeys)) {
218
+ const v = getNestedPath(headObj, path);
219
+ if (v !== void 0) out[flatKey] = v;
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ var NOT_AUTHENTICATED_CODE = "not-authenticated";
225
+ var OP_MAP = {
226
+ eq: "_eq",
227
+ neq: "_neq",
228
+ ne: "_neq",
229
+ lt: "_lt",
230
+ lte: "_lte",
231
+ gt: "_gt",
232
+ gte: "_gte",
233
+ in: "_in",
234
+ notIn: "_nin",
235
+ nin: "_nin",
236
+ contains: "_ilike",
237
+ containss: "_like",
238
+ startsWith: "_ilike",
239
+ endsWith: "_ilike",
240
+ startswith: "_ilike",
241
+ endswith: "_ilike",
242
+ null: "_is_null"
243
+ };
244
+ var FILTER_OPERATOR_UNSUPPORTED_CODE = "filter-operator-unsupported";
245
+ var UNEXPRESSIBLE_OPS = {
246
+ has: "a collection-membership test",
247
+ hasAny: "a collection-membership test",
248
+ hasAll: "a collection-membership test"
249
+ };
250
+ function unsupportedOperator(field, op) {
251
+ const why = UNEXPRESSIBLE_OPS[op];
252
+ return {
253
+ kind: "capability",
254
+ code: FILTER_OPERATOR_UNSUPPORTED_CODE,
255
+ message: why ? `@burojs/hasura cannot express the '${op}' filter operator on '${field}': ${why}, whose Hasura encoding depends on whether the column is jsonb or a Postgres array \u2014 something no ResourceMapping field declares. Declare it and translate explicitly, or filter on a scalar column.` : `@burojs/hasura does not support the filter operator '${op}' (on '${field}').`
256
+ };
257
+ }
258
+ function scopeToWhere(scope, scopeFields) {
259
+ const clauses = [];
260
+ for (const key of scopeFields) {
261
+ const v = scope[key];
262
+ if (v == null || v === "") continue;
263
+ clauses.push({ [key]: { _eq: v } });
264
+ }
265
+ if (clauses.length === 0) return void 0;
266
+ if (clauses.length === 1) return clauses[0];
267
+ return { _and: clauses };
268
+ }
269
+ function mergeWhere(a, b) {
270
+ if (!a) return b;
271
+ if (!b) return a;
272
+ return { _and: [a, b] };
273
+ }
274
+ function filtersToWhere(filter) {
275
+ if (!filter || typeof filter !== "object") return void 0;
276
+ if ("and" in filter) {
277
+ if (filter.and.length === 0) return { _and: [] };
278
+ const clauses = filter.and.map(filtersToWhere).filter((item) => item !== void 0);
279
+ if (clauses.length === 0) return void 0;
280
+ return clauses.length === 1 ? clauses[0] : { _and: clauses };
281
+ }
282
+ if ("or" in filter) {
283
+ if (filter.or.length === 0) return { _or: [] };
284
+ const clauses = filter.or.map(filtersToWhere).filter((item) => item !== void 0);
285
+ if (clauses.length === 0) return void 0;
286
+ return clauses.length === 1 ? clauses[0] : { _or: clauses };
287
+ }
288
+ if ("not" in filter) {
289
+ const clause = filtersToWhere(filter.not);
290
+ return clause === void 0 ? void 0 : { _not: clause };
291
+ }
292
+ if (!("field" in filter) || typeof filter.field !== "string" || !("op" in filter))
293
+ return void 0;
294
+ const { field, op } = filter;
295
+ if (op === "isNull") return { [field]: { _is_null: true } };
296
+ if (op === "isNotNull") return { [field]: { _is_null: false } };
297
+ if (!("value" in filter) || filter.value === void 0) return void 0;
298
+ const operator = OP_MAP[op];
299
+ if (operator === void 0) throw unsupportedOperator(field, op);
300
+ let value = filter.value;
301
+ if (operator === "_ilike" || operator === "_like") {
302
+ const text = String(value);
303
+ value = op === "startsWith" ? `${text}%` : op === "endsWith" ? `%${text}` : `%${text}%`;
304
+ }
305
+ return { [field]: { [operator]: value } };
306
+ }
307
+ function coerceInt64Filter(filter, fields) {
308
+ if (!filter || !fields?.length) return filter;
309
+ if ("and" in filter)
310
+ return {
311
+ and: filter.and.map(
312
+ (entry) => coerceInt64Filter(entry, fields)
313
+ )
314
+ };
315
+ if ("or" in filter)
316
+ return {
317
+ or: filter.or.map(
318
+ (entry) => coerceInt64Filter(entry, fields)
319
+ )
320
+ };
321
+ if ("not" in filter)
322
+ return { not: coerceInt64Filter(filter.not, fields) };
323
+ if ("field" in filter && fields.includes(filter.field) && "value" in filter && filter.value != null) {
324
+ const value = Array.isArray(filter.value) ? filter.value.map(String) : String(filter.value);
325
+ return { ...filter, value };
326
+ }
327
+ return filter;
328
+ }
329
+ function hasuraError(error, signal, fallback) {
330
+ if (core.isDataError(error)) return error;
331
+ if (signal.aborted)
332
+ return {
333
+ kind: "cancelled",
334
+ code: "request-aborted",
335
+ message: "Hasura request was aborted.",
336
+ cause: error
337
+ };
338
+ return {
339
+ kind: "transport",
340
+ code: "hasura-request-failed",
341
+ message: error instanceof Error && error.message ? error.message : fallback,
342
+ cause: error
343
+ };
344
+ }
345
+ function aggregateRoot(m) {
346
+ if (m.aggregate === false) return null;
347
+ return typeof m.aggregate === "string" ? m.aggregate : `${m.table}_aggregate`;
348
+ }
349
+ function byPkRoot(m) {
350
+ if (m.byPkRoot === false) return null;
351
+ return m.byPkRoot ?? `${m.table}_by_pk`;
352
+ }
353
+ function snapshotOperationRegistry(source) {
354
+ if (source === void 0) return Object.freeze({});
355
+ const resources = {};
356
+ for (const [resource, operations] of Object.entries(source)) {
357
+ const entries = {};
358
+ for (const [name, operation] of Object.entries(operations)) {
359
+ entries[name] = Object.freeze({ ...operation });
360
+ }
361
+ resources[resource] = Object.freeze(entries);
362
+ }
363
+ return Object.freeze(resources);
364
+ }
365
+ function hasRegisteredOperationKind(operations, kind) {
366
+ return Object.values(operations).some(
367
+ (byName) => Object.values(byName).some((operation) => operation.kind === kind)
368
+ );
369
+ }
370
+ function normalizeRole(role) {
371
+ return role === void 0 || role === null || role === "" ? null : role;
372
+ }
373
+ function createHasuraDataProvider(config) {
374
+ const endpoint = config.endpoint ?? DEFAULT_HASURA_ENDPOINT;
375
+ const defaultRole = normalizeRole(config.defaultRole);
376
+ const operations = snapshotOperationRegistry(config.operations);
377
+ const hasCustomQueries = hasRegisteredOperationKind(operations, "query");
378
+ const hasCustomMutations = hasRegisteredOperationKind(operations, "mutation");
379
+ async function gql(query, variables, role, signal) {
380
+ try {
381
+ const request = async (token2) => {
382
+ const headers = {
383
+ "Content-Type": "application/json",
384
+ Authorization: `Bearer ${token2}`
385
+ };
386
+ const effectiveRole = role === void 0 ? defaultRole : normalizeRole(role);
387
+ if (effectiveRole !== null) headers["X-Hasura-Role"] = effectiveRole;
388
+ const fetchImpl = config.fetchImpl ?? fetch;
389
+ return fetchImpl(endpoint, {
390
+ method: "POST",
391
+ headers,
392
+ body: JSON.stringify({ query, variables }),
393
+ signal
394
+ });
395
+ };
396
+ let token = await config.getToken();
397
+ if (!token)
398
+ throw {
399
+ kind: "auth",
400
+ code: NOT_AUTHENTICATED_CODE,
401
+ message: "Not authenticated."
402
+ };
403
+ let res = await request(token);
404
+ if (res.status === 401 && config.recoverAuth && await config.recoverAuth()) {
405
+ token = await config.getToken();
406
+ if (!token)
407
+ throw {
408
+ kind: "auth",
409
+ code: NOT_AUTHENTICATED_CODE,
410
+ message: "Not authenticated."
411
+ };
412
+ res = await request(token);
413
+ }
414
+ if (!res.ok)
415
+ throw {
416
+ kind: "transport",
417
+ code: "graphql-http-error",
418
+ message: `GraphQL HTTP ${res.status}`,
419
+ status: res.status
420
+ };
421
+ const body = await res.json();
422
+ if (body.errors?.length)
423
+ throw {
424
+ kind: "protocol",
425
+ code: "graphql-error",
426
+ message: body.errors.map((e) => e.message).join("; "),
427
+ details: body.errors
428
+ };
429
+ if (body.data === void 0)
430
+ throw {
431
+ kind: "protocol",
432
+ code: "empty-graphql-response",
433
+ message: "Empty GraphQL response."
434
+ };
435
+ return body.data;
436
+ } catch (error) {
437
+ throw hasuraError(error, signal, "Hasura request failed.");
438
+ }
439
+ }
440
+ function mapping(resource) {
441
+ const m = config.resources[resource];
442
+ if (!m)
443
+ throw {
444
+ kind: "configuration",
445
+ code: "unknown-resource",
446
+ message: `Unknown resource: ${resource}`
447
+ };
448
+ return m;
449
+ }
450
+ function registeredOperation(resource, operation, kind) {
451
+ const registered = operations[resource]?.[operation];
452
+ if (registered === void 0 || registered.kind !== kind) {
453
+ throw {
454
+ kind: "capability",
455
+ code: "hasura-custom-operation-unsupported",
456
+ message: `Hasura ${kind} operation '${operation}' is not declared for '${resource}'.`
457
+ };
458
+ }
459
+ return registered;
460
+ }
461
+ async function executeCustomOperation(resource, operationName, input, kind, signal) {
462
+ const operation = registeredOperation(resource, operationName, kind);
463
+ const result = await gql(
464
+ operation.document,
465
+ operation.variables(input),
466
+ operation.role ?? config.resources[resource]?.role,
467
+ signal
468
+ );
469
+ return operation.mapResult?.(result) ?? result;
470
+ }
471
+ function composeListWhere(m, descriptor, context) {
472
+ const userWhere = filtersToWhere(coerceInt64Filter(descriptor.filter, m.int64Fields));
473
+ const ignoreScope = descriptor.providerOptions?.ignoreScope === true;
474
+ const sessionScope = context.session.scopeKey !== null && typeof context.session.scopeKey === "object" && !Array.isArray(context.session.scopeKey) ? context.session.scopeKey : {};
475
+ const scope = ignoreScope ? {} : { ...sessionScope, ...config.getScope?.(context) ?? {} };
476
+ const scopeWhere = scopeToWhere(scope, m.scopeFields ?? []);
477
+ return mergeWhere(mergeWhere(userWhere, scopeWhere), m.fixedFilter);
478
+ }
479
+ async function runAggregateCount(m, root, where, signal) {
480
+ const aggWhereArg = where ? "($where: " + m.table + "_bool_exp)" : "";
481
+ const aggWhereParam = where ? "(where: $where)" : "";
482
+ const metaQuery = `query Count_${m.table} ${aggWhereArg} {
483
+ meta: ${root} ${aggWhereParam} { aggregate { count } }
484
+ }`;
485
+ const aggVars = {};
486
+ if (where) aggVars["where"] = where;
487
+ const metaData = await gql(
488
+ metaQuery,
489
+ where ? aggVars : void 0,
490
+ m.role,
491
+ signal
492
+ );
493
+ return metaData.meta.aggregate.count;
494
+ }
495
+ async function upsertDataBody(db, parentId, body, role, signal) {
496
+ const mutation = `mutation UpsertDataBody($object: ${db.table}_insert_input!) {
497
+ result: insert_${db.table}_one(
498
+ object: $object,
499
+ on_conflict: { constraint: ${db.constraint}, update_columns: [${db.column}] }
500
+ ) { ${db.fk} }
501
+ }`;
502
+ await gql(mutation, { object: { [db.fk]: parentId, [db.column]: body } }, role, signal);
503
+ }
504
+ function mutationRecord(m, idField, item, resource, expectedId) {
505
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
506
+ throw {
507
+ kind: "protocol",
508
+ code: "record-not-found",
509
+ message: `Not found: ${resource}`
510
+ };
511
+ }
512
+ const record = item;
513
+ const id = record[m.pkField ?? idField];
514
+ if (typeof id !== "string" && (typeof id !== "number" || !Number.isFinite(id))) {
515
+ throw {
516
+ kind: "protocol",
517
+ code: "mutation-record-id-missing",
518
+ message: `Mutation for '${resource}' returned no valid '${m.pkField ?? idField}'.`
519
+ };
520
+ }
521
+ if (expectedId !== void 0 && id !== expectedId) {
522
+ throw {
523
+ kind: "protocol",
524
+ code: "unexpected-record-id",
525
+ message: `Mutation for '${resource}' returned '${String(id)}' instead of '${String(expectedId)}'.`
526
+ };
527
+ }
528
+ return { kind: "record", id, record: item, completeness: "partial" };
529
+ }
530
+ async function readMutationRecord(m, id, signal) {
531
+ const fields = m.selectFields.join(" ");
532
+ const pkType = m.pkType ?? "bigint";
533
+ const pkField = m.pkField ?? "id";
534
+ const root = byPkRoot(m);
535
+ if (m.fixedFilter || root === null) {
536
+ const where = mergeWhere({ [pkField]: { _eq: id } }, m.fixedFilter);
537
+ const query2 = `query One_${m.table}($where: ${m.table}_bool_exp) {
538
+ items: ${m.table}(where: $where, limit: 1) { ${fields} }
539
+ }`;
540
+ const data2 = await gql(query2, { where }, m.role, signal);
541
+ return data2.items?.[0] ?? null;
542
+ }
543
+ const query = `query One_${m.table}($id: ${pkType}!) {
544
+ item: ${root}(${pkField}: $id) { ${fields} }
545
+ }`;
546
+ const data = await gql(query, { id }, m.role, signal);
547
+ return data.item;
548
+ }
549
+ return core.defineDataProvider({
550
+ queries: {
551
+ async list(descriptor, context) {
552
+ const m = mapping(descriptor.resource);
553
+ if (descriptor.pagination?.kind === "cursor") {
554
+ throw {
555
+ kind: "capability",
556
+ code: "cursor-pagination-unsupported",
557
+ message: "Hasura provider supports offset pagination only."
558
+ };
559
+ }
560
+ const limit = descriptor.pagination?.kind === "offset" ? descriptor.pagination.pageSize : 25;
561
+ const page = descriptor.pagination?.kind === "offset" ? descriptor.pagination.page : 1;
562
+ const offset = (page - 1) * limit;
563
+ const where = composeListWhere(m, descriptor, context);
564
+ const sorters = descriptor.sort?.filter((s) => s.field);
565
+ let orderByExpr;
566
+ if (sorters && sorters.length > 0) {
567
+ orderByExpr = `[${sorters.map((s) => `{${s.field}: ${s.direction}}`).join(", ")}]`;
568
+ } else {
569
+ const defaultField = m.orderByField ?? "id";
570
+ orderByExpr = `{${defaultField}: desc}`;
571
+ }
572
+ const fields = m.selectFields.join(" ");
573
+ const whereArg = where ? ", $where: " + m.table + "_bool_exp" : "";
574
+ const whereParam = where ? ", where: $where" : "";
575
+ const itemsQuery = `query List_${m.table}($limit: Int, $offset: Int${whereArg}) {
576
+ items: ${m.table}(limit: $limit, offset: $offset, order_by: ${orderByExpr}${whereParam}) { ${fields} }
577
+ }`;
578
+ const itemsVars = { limit, offset };
579
+ if (where) itemsVars["where"] = where;
580
+ const itemsData = await gql(
581
+ itemsQuery,
582
+ itemsVars,
583
+ m.role,
584
+ context.signal
585
+ );
586
+ let total;
587
+ const listAggRoot = aggregateRoot(m);
588
+ if (!m.noAggregate && listAggRoot) {
589
+ try {
590
+ total = await runAggregateCount(m, listAggRoot, where, context.signal);
591
+ } catch (err) {
592
+ console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
593
+ }
594
+ }
595
+ const spill = m.jsonbSpill;
596
+ const items = spill ? itemsData.items.map((it) => flattenJsonbSpill(it, spill)) : itemsData.items;
597
+ return { data: items, total };
598
+ },
599
+ /**
600
+ * On-demand row count — the answer to "how many are there?" on the lists
601
+ * that page without a grand total (`noAggregate`). Never fired implicitly:
602
+ * one source app measured ~55 s for a single COUNT, which is exactly why
603
+ * the list stopped issuing one on every page.
604
+ *
605
+ * `{ total: null }` means "not countable here at all" — the registry says
606
+ * this table has no aggregate root, or the resource isn't mapped by this
607
+ * provider. It is a DECISION, and the UI latches the affordance off for the
608
+ * session. A transient backend failure REJECTS instead (it propagates out of
609
+ * `gql`), so a retry stays possible; never conflate the two.
610
+ *
611
+ * The `where` comes from the same {@link composeListWhere} `getList` uses —
612
+ * same filters, same scope, same `fixedFilter` — so the number always
613
+ * describes the rows the list is paging through.
614
+ */
615
+ async count(descriptor, context) {
616
+ const m = config.resources[descriptor.resource];
617
+ if (!m) return { total: null };
618
+ const root = aggregateRoot(m);
619
+ if (!root) return { total: null };
620
+ return {
621
+ total: await runAggregateCount(
622
+ m,
623
+ root,
624
+ composeListWhere(m, descriptor, context),
625
+ context.signal
626
+ )
627
+ };
628
+ },
629
+ async many(descriptor, context) {
630
+ const m = mapping(descriptor.resource);
631
+ if (descriptor.ids.length === 0) return { data: [] };
632
+ const pkField = m.pkField ?? "id";
633
+ const idsWhere = { [pkField]: { _in: descriptor.ids } };
634
+ const where = mergeWhere(
635
+ idsWhere,
636
+ composeListWhere(m, descriptor, context)
637
+ );
638
+ const fields = m.selectFields.join(" ");
639
+ const query = `query Many_${m.table}($where: ${m.table}_bool_exp) {
640
+ items: ${m.table}(where: $where) { ${fields} }
641
+ }`;
642
+ const data = await gql(query, { where }, m.role, context.signal);
643
+ const spill = m.jsonbSpill;
644
+ const items = spill ? data.items.map((item) => flattenJsonbSpill(item, spill)) : data.items;
645
+ return { data: items };
646
+ },
647
+ async one(descriptor, context) {
648
+ const m = mapping(descriptor.resource);
649
+ const dbSelect = m.dataBody ? ` ${m.dataBody.relationship} { ${m.dataBody.column} }` : "";
650
+ const fields = m.selectFields.join(" ") + dbSelect;
651
+ const pkType = m.pkType ?? "bigint";
652
+ const pkField = m.pkField ?? "id";
653
+ let item;
654
+ const root = byPkRoot(m);
655
+ if (m.fixedFilter || root === null) {
656
+ const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
657
+ const query = `query One_${m.table}($where: ${m.table}_bool_exp) {
658
+ items: ${m.table}(where: $where, limit: 1) { ${fields} }
659
+ }`;
660
+ const data = await gql(query, { where }, m.role, context.signal);
661
+ item = data.items?.[0] ?? null;
662
+ } else {
663
+ const query = `query One_${m.table}($id: ${pkType}!) {
664
+ item: ${root}(${pkField}: $id) { ${fields} }
665
+ }`;
666
+ const data = await gql(
667
+ query,
668
+ { id: descriptor.id },
669
+ m.role,
670
+ context.signal
671
+ );
672
+ item = data.item;
673
+ }
674
+ if (item == null)
675
+ throw {
676
+ kind: "protocol",
677
+ code: "record-not-found",
678
+ message: `Not found: ${descriptor.resource}/${descriptor.id}`
679
+ };
680
+ let result = m.jsonbSpill ? flattenJsonbSpill(item, m.jsonbSpill) : item;
681
+ if (m.dataBody && result && typeof result === "object") {
682
+ const rec = { ...result };
683
+ const sibling = rec[m.dataBody.relationship];
684
+ const body = sibling && typeof sibling === "object" ? sibling[m.dataBody.column] : null;
685
+ delete rec[m.dataBody.relationship];
686
+ result = body && typeof body === "object" ? { ...rec, ...body } : rec;
687
+ }
688
+ return { data: result };
689
+ },
690
+ ...hasCustomQueries ? {
691
+ async custom(descriptor, context) {
692
+ return executeCustomOperation(
693
+ descriptor.resource,
694
+ descriptor.operation,
695
+ descriptor.input,
696
+ "query",
697
+ context.signal
698
+ );
699
+ }
700
+ } : {}
701
+ },
702
+ mutations: {
703
+ async createOne(descriptor, context) {
704
+ const m = mapping(descriptor.resource);
705
+ const fields = m.selectFields.join(" ");
706
+ const rawInput = descriptor.input;
707
+ let mainInput = rawInput;
708
+ let dataBody;
709
+ if (m.dataBody) {
710
+ const split = partitionDataBody(rawInput, m.dataBody);
711
+ mainInput = split.rest;
712
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
713
+ }
714
+ const object = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
715
+ const query = `mutation Create_${m.table}($object: ${m.table}_insert_input!) {
716
+ item: insert_${m.table}_one(object: $object) { ${fields} }
717
+ }`;
718
+ const data = await gql(query, { object }, m.role, context.signal);
719
+ const result = mutationRecord(m, descriptor.idField, data.item, descriptor.resource);
720
+ if (m.dataBody && dataBody)
721
+ await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
722
+ return result;
723
+ },
724
+ async updateOne(descriptor, context) {
725
+ const m = mapping(descriptor.resource);
726
+ const fields = m.selectFields.join(" ");
727
+ const rawInput = descriptor.input;
728
+ let mainInput = rawInput;
729
+ let dataBody;
730
+ if (m.dataBody) {
731
+ const split = partitionDataBody(rawInput, m.dataBody);
732
+ mainInput = split.rest;
733
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
734
+ }
735
+ const set = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
736
+ const pkField = m.pkField ?? descriptor.idField;
737
+ const ifUpdatedAt = descriptor.providerOptions?.ifUpdatedAt;
738
+ let item;
739
+ if (Object.keys(set).length === 0) {
740
+ item = await readMutationRecord(m, descriptor.id, context.signal);
741
+ } else if (m.fixedFilter || ifUpdatedAt != null) {
742
+ let where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
743
+ if (ifUpdatedAt != null) where = mergeWhere(where, { updated_at: { _eq: ifUpdatedAt } });
744
+ const query = `mutation Update_${m.table}($where: ${m.table}_bool_exp!, $set: ${m.table}_set_input!) {
745
+ result: update_${m.table}(where: $where, _set: $set) { affected_rows returning { ${fields} } }
746
+ }`;
747
+ const data = await gql(
748
+ query,
749
+ { where, set },
750
+ m.role,
751
+ context.signal
752
+ );
753
+ if (ifUpdatedAt != null && ((data.result.affected_rows ?? 0) === 0 || (data.result.returning?.length ?? 0) === 0)) {
754
+ throw {
755
+ kind: "conflict",
756
+ code: "stale-record",
757
+ message: `Update for '${descriptor.resource}/${descriptor.id}' matched no row: the record was changed since it was loaded.`
758
+ };
759
+ }
760
+ item = data.result.returning?.[0] ?? null;
761
+ } else {
762
+ const pkType = m.pkType ?? "bigint";
763
+ const query = `mutation Update_${m.table}($id: ${pkType}!, $set: ${m.table}_set_input!) {
764
+ item: update_${m.table}_by_pk(pk_columns: {${pkField}: $id}, _set: $set) { ${fields} }
765
+ }`;
766
+ const data = await gql(
767
+ query,
768
+ { id: descriptor.id, set },
769
+ m.role,
770
+ context.signal
771
+ );
772
+ item = data.item;
773
+ }
774
+ const result = mutationRecord(
775
+ m,
776
+ descriptor.idField,
777
+ item,
778
+ descriptor.resource,
779
+ descriptor.id
780
+ );
781
+ if (m.dataBody && dataBody)
782
+ await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
783
+ return result;
784
+ },
785
+ async deleteOne(descriptor, context) {
786
+ const m = mapping(descriptor.resource);
787
+ const fields = m.selectFields.join(" ");
788
+ const pkField = m.pkField ?? descriptor.idField;
789
+ let item;
790
+ if (m.fixedFilter) {
791
+ const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
792
+ const query = `mutation Delete_${m.table}($where: ${m.table}_bool_exp!) {
793
+ result: delete_${m.table}(where: $where) { affected_rows returning { ${fields} } }
794
+ }`;
795
+ const data = await gql(
796
+ query,
797
+ { where },
798
+ m.role,
799
+ context.signal
800
+ );
801
+ item = data.result.returning?.[0] ?? null;
802
+ } else {
803
+ const pkType = m.pkType ?? "bigint";
804
+ const query = `mutation Delete_${m.table}($id: ${pkType}!) {
805
+ item: delete_${m.table}_by_pk(${pkField}: $id) { ${fields} }
806
+ }`;
807
+ const data = await gql(
808
+ query,
809
+ { id: descriptor.id },
810
+ m.role,
811
+ context.signal
812
+ );
813
+ item = data.item;
814
+ }
815
+ mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
816
+ return { kind: "identity", id: descriptor.id };
817
+ },
818
+ ...hasCustomMutations ? {
819
+ async custom(descriptor, context) {
820
+ return executeCustomOperation(
821
+ descriptor.resource,
822
+ descriptor.operation,
823
+ descriptor.input,
824
+ "mutation",
825
+ context.signal
826
+ );
827
+ }
828
+ } : {}
829
+ },
830
+ live: createHasuraLiveProvider({
831
+ resources: config.resources,
832
+ getToken: config.getToken,
833
+ endpoint,
834
+ role: defaultRole
835
+ })
836
+ });
837
+ }
838
+
839
+ exports.DEFAULT_HASURA_ENDPOINT = DEFAULT_HASURA_ENDPOINT;
840
+ exports.FILTER_OPERATOR_UNSUPPORTED_CODE = FILTER_OPERATOR_UNSUPPORTED_CODE;
841
+ exports.NOT_AUTHENTICATED_CODE = NOT_AUTHENTICATED_CODE;
842
+ exports.aggregateRoot = aggregateRoot;
843
+ exports.byPkRoot = byPkRoot;
844
+ exports.createHasuraDataProvider = createHasuraDataProvider;
845
+ exports.createHasuraLiveProvider = createHasuraLiveProvider;
846
+ exports.filtersToWhere = filtersToWhere;
847
+ exports.flattenJsonbSpill = flattenJsonbSpill;
848
+ exports.hasuraWsUrl = hasuraWsUrl;
849
+ exports.mergeWhere = mergeWhere;
850
+ exports.partitionDataBody = partitionDataBody;
851
+ exports.partitionJsonbSpill = partitionJsonbSpill;
852
+ exports.scopeToWhere = scopeToWhere;
853
+ //# sourceMappingURL=index.cjs.map
854
+ //# sourceMappingURL=index.cjs.map