@stonecrop/graphql-middleware 0.16.6 → 0.17.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.js CHANGED
@@ -1,142 +1,178 @@
1
- import { readdirSync as et, statSync as nt, readFileSync as ot } from "node:fs";
2
- import { join as rt } from "node:path";
3
- import { validateDoctype as Z, parseDoctype as tt, isActionAllowedInState as st, camelToSnake as A, getPrimaryKeyField as it, pascalToSnake as at, resolveLinkRenderMode as ct } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as lt, loadOneWithPgClient as X } from "@dataplan/pg";
5
- import { object as q, constant as ut, lambda as dt } from "postgraphile/grafast";
6
- import { gql as ft, extendSchema as pt, wrapPlans as gt } from "postgraphile/utils";
7
- import { PostGraphileAmberPreset as yt } from "postgraphile/presets/amber";
8
- import { makePgService as qt } from "postgraphile/adaptors/pg";
9
- const w = /* @__PURE__ */ new Map();
10
- class V extends Error {
11
- constructor(e, o) {
12
- const n = o.map((s) => ` ${s.path.join(".")}: ${s.message}`).join(`
1
+ import { readdirSync as re, statSync as se, readFileSync as ie } from "node:fs";
2
+ import { join as ae } from "node:path";
3
+ import { validateDoctype as te, parseDoctype as ne, isActionAllowedInState as ce, camelToSnake as D, pascalToSnake as le, getRecordIdField as de, resolveLinkRenderMode as ue } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as fe, loadOneWithPgClient as Z } from "@dataplan/pg";
5
+ import { object as _, constant as ge, lambda as pe } from "postgraphile/grafast";
6
+ import { gql as he, extendSchema as ye, wrapPlans as me } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as we } from "postgraphile/presets/amber";
8
+ import { makePgService as Ge } from "postgraphile/adaptors/pg";
9
+ const C = /* @__PURE__ */ new Map();
10
+ class G extends Error {
11
+ constructor(t, o) {
12
+ const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
13
13
  `);
14
- super(`Invalid doctype definition in ${e}:
15
- ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
14
+ super(`Invalid doctype definition in ${t}:
15
+ ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
16
16
  }
17
17
  file;
18
18
  errors;
19
19
  }
20
- function St(t, e = {}) {
21
- const o = et(t);
20
+ function Se(e, t = {}) {
21
+ const o = re(e);
22
22
  for (const n of o) {
23
- const s = rt(t, n);
24
- nt(s).isDirectory() ? St(s, e) : n.endsWith(".json") && mt(s, e);
23
+ const r = ae(e, n);
24
+ se(r).isDirectory() ? Se(r, t) : n.endsWith(".json") && $e(r, t);
25
25
  }
26
26
  }
27
- function mt(t, e) {
28
- const o = ot(t, "utf-8");
27
+ function $e(e, t) {
28
+ const o = ie(e, "utf-8");
29
29
  let n;
30
30
  try {
31
31
  n = JSON.parse(o);
32
- } catch (f) {
33
- const y = {
32
+ } catch (l) {
33
+ const d = {
34
34
  path: [],
35
- message: `Invalid JSON: ${f instanceof Error ? f.message : String(f)}`
35
+ message: `Invalid JSON: ${l instanceof Error ? l.message : String(l)}`
36
36
  };
37
- if (e.continueOnError) {
38
- e.onError?.(t, [y]);
37
+ if (t.continueOnError) {
38
+ t.onError?.(e, [d]);
39
39
  return;
40
40
  }
41
- throw new V(t, [y]);
41
+ throw new G(e, [d]);
42
42
  }
43
- const s = Z(n);
44
- if (!s.success) {
45
- if (e.continueOnError) {
46
- e.onError?.(t, s.errors);
43
+ const r = te(n);
44
+ if (!r.success) {
45
+ if (t.continueOnError) {
46
+ t.onError?.(e, r.errors);
47
47
  return;
48
48
  }
49
- throw new V(t, s.errors);
49
+ throw new G(e, r.errors);
50
50
  }
51
- const l = tt(n);
52
- w.set(l.name, l);
51
+ const i = ne(n);
52
+ C.set(i.name, i);
53
53
  }
54
- function Nt(t, e = {}) {
55
- for (const [o, n] of Object.entries(t)) {
56
- const s = { ...typeof n == "object" && n !== null ? n : {}, name: o }, l = Z(s);
57
- if (!l.success) {
58
- if (e.continueOnError) {
59
- e.onError?.(o, l.errors);
54
+ function Le(e, t = {}) {
55
+ for (const [o, n] of Object.entries(e)) {
56
+ const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = te(r);
57
+ if (!i.success) {
58
+ if (t.continueOnError) {
59
+ t.onError?.(o, i.errors);
60
60
  continue;
61
61
  }
62
- throw new V(o, l.errors);
62
+ throw new G(o, i.errors);
63
63
  }
64
- const f = tt(s);
65
- w.set(f.name, f);
64
+ const l = ne(r);
65
+ C.set(l.name, l);
66
66
  }
67
67
  }
68
- function T(t) {
69
- const e = w.get(t);
70
- if (e) return e;
71
- for (const o of w.values())
72
- if (o.slug === t) return o;
68
+ function M(e) {
69
+ const t = C.get(e);
70
+ if (t) return t;
71
+ for (const o of C.values())
72
+ if (o.slug === e) return o;
73
73
  }
74
- function wt() {
75
- return Array.from(w.values());
74
+ function oe() {
75
+ return Array.from(C.values());
76
76
  }
77
- function It(t) {
78
- return w.has(t);
77
+ function Pe(e) {
78
+ return C.has(e);
79
79
  }
80
- function Dt() {
81
- w.clear();
80
+ function We() {
81
+ C.clear();
82
82
  }
83
- function Lt() {
84
- const t = [];
85
- for (const e of w.values()) {
86
- e.inherits && !w.has(e.inherits) && t.push({
87
- path: [e.name, "inherits"],
88
- message: `References unknown doctype: ${e.inherits}`
83
+ function ke() {
84
+ const e = [];
85
+ for (const t of C.values()) {
86
+ t.inherits && M(t.inherits) === void 0 && e.push({
87
+ path: [t.name, "inherits"],
88
+ message: `References unknown doctype: ${t.inherits}`
89
89
  });
90
- for (const o of e.fields) {
90
+ for (const o of t.fields) {
91
91
  if (o.kind !== "field") continue;
92
92
  const n = o.doctype;
93
- n !== void 0 && !w.has(n) && t.push({
94
- path: [e.name, "fields", o.fieldname, "doctype"],
93
+ n !== void 0 && M(n) === void 0 && e.push({
94
+ path: [t.name, "fields", o.fieldname, "doctype"],
95
95
  message: `Link references unknown doctype: ${n}`
96
96
  });
97
97
  }
98
- if (e.links)
99
- for (const [o, n] of Object.entries(e.links))
100
- w.has(n.target) || t.push({
101
- path: [e.name, "links", o, "target"],
98
+ if (t.links)
99
+ for (const [o, n] of Object.entries(t.links))
100
+ M(n.target) === void 0 && e.push({
101
+ path: [t.name, "links", o, "target"],
102
102
  message: `Link references unknown doctype: ${n.target}`
103
103
  });
104
104
  }
105
- return t;
105
+ return e;
106
106
  }
107
- const G = /* @__PURE__ */ new Map();
108
- function Tt(t, e) {
109
- G.set(t, e);
107
+ const K = /* @__PURE__ */ new Map();
108
+ function qe(e, t) {
109
+ K.set(e, t);
110
110
  }
111
- function ht(t) {
112
- return G.get(t);
111
+ function Ee(e) {
112
+ return K.get(e);
113
113
  }
114
- function Pt() {
115
- G.clear();
114
+ function He() {
115
+ K.clear();
116
116
  }
117
- async function $t(t, e, o) {
118
- if (!t.selfTransition && t.nextState == null)
117
+ async function be(e, t, o) {
118
+ const n = e.label ?? "unknown", r = e.selfTransition === !0, i = r || e.nextState != null;
119
+ if (!i && !t.runEffect)
119
120
  return {
120
121
  success: !1,
121
122
  data: null,
122
- error: `Action "${t.label ?? "unknown"}" has no workflow transition and no server-side effect is wired — nothing was executed.`
123
+ error: `Action "${n}" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`
123
124
  };
124
- const n = await e.readState() ?? "";
125
- return st(t, n) ? t.selfTransition ? e.writeData ? { success: !0, data: await e.writeData(o ?? {}), error: null } : {
126
- success: !1,
127
- data: null,
128
- error: `Action "${t.label ?? "unknown"}" persists record data in place, which this backend does not support.`
129
- } : t.nextState == null ? { success: !1, data: null, error: "nothing was executed" } : (await e.writeState(t.nextState), {
125
+ if (r && !t.writeData && !t.runEffect)
126
+ return {
127
+ success: !1,
128
+ data: null,
129
+ error: `Action "${n}" persists record data in place, which this backend does not support.`
130
+ };
131
+ const l = (e.allowedStates?.length ?? 0) > 0;
132
+ let d;
133
+ if (l || i) {
134
+ const h = await t.readState();
135
+ if (h === null) {
136
+ if (r && t.writeData) {
137
+ const a = await t.writeData(o ?? {}, !1);
138
+ return !a || Object.keys(a).length === 0 ? {
139
+ success: !1,
140
+ data: null,
141
+ error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
142
+ } : { success: !0, data: a, error: null };
143
+ }
144
+ return {
145
+ success: !1,
146
+ data: null,
147
+ error: `Action "${n}" targets a record that does not exist — nothing was executed.`
148
+ };
149
+ }
150
+ d = h ?? "";
151
+ }
152
+ if (!ce(e, d ?? ""))
153
+ return {
154
+ success: !1,
155
+ data: null,
156
+ error: `Action not allowed from state: ${d || "(unknown)"}`
157
+ };
158
+ let S;
159
+ if (t.runEffect)
160
+ try {
161
+ S = await t.runEffect(d);
162
+ } catch (h) {
163
+ return {
164
+ success: !1,
165
+ data: null,
166
+ error: `Action "${n}" failed: ${h instanceof Error ? h.message : String(h)}`
167
+ };
168
+ }
169
+ return r ? { success: !0, data: (t.writeData ? await t.writeData(o ?? {}, !0) : S) ?? null, error: null } : e.nextState == null ? { success: !0, data: S ?? null, error: null } : (await t.writeState(e.nextState), {
130
170
  success: !0,
131
- data: { state: t.nextState },
171
+ data: S ?? { state: e.nextState },
132
172
  error: null
133
- }) : {
134
- success: !1,
135
- data: null,
136
- error: `Action not allowed from state: ${n || "(unknown)"}`
137
- };
173
+ });
138
174
  }
139
- const kt = ft`
175
+ const ve = he`
140
176
  type StonecropFieldMeta {
141
177
  kind: String!
142
178
  fieldname: String!
@@ -194,7 +230,16 @@ const kt = ft`
194
230
  type StonecropRecordsResult {
195
231
  data: [JSON!]!
196
232
  doctype: String!
197
- count: Int!
233
+ """
234
+ Whether further records exist beyond this page. Always answered — it is read from the
235
+ page itself (one extra row is requested and discarded), so it costs no second query.
236
+ """
237
+ hasMore: Boolean!
238
+ """
239
+ Total matching the filters, ignoring limit/offset. Null unless the query asked for it
240
+ with includeTotal, because counting is a full scan on most backends.
241
+ """
242
+ count: Int
198
243
  }
199
244
 
200
245
  type StonecropActionResult {
@@ -213,6 +258,7 @@ const kt = ft`
213
258
  orderBy: String
214
259
  limit: Int
215
260
  offset: Int
261
+ includeTotal: Boolean
216
262
  options: JSON
217
263
  ): StonecropRecordsResult
218
264
  }
@@ -220,165 +266,177 @@ const kt = ft`
220
266
  extend type Mutation {
221
267
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
222
268
  }
223
- `, jt = (t = {}) => {
224
- const e = t.debug ? (o, n) => (console.log(`[@stonecrop/graphql-middleware] ${n.text}`, n.values ?? []), o.query(n)) : (o, n) => o.query(n);
225
- return pt((o) => {
226
- const n = o.input?.pgRegistry?.pgExecutors, s = n ? Object.values(n)[0] : void 0;
227
- if (!s)
269
+ `;
270
+ class ee extends Error {
271
+ constructor(t) {
272
+ super(t.error ?? "Action failed"), this.outcome = t, this.name = "ActionRolledBack";
273
+ }
274
+ outcome;
275
+ }
276
+ const Je = (e = {}) => {
277
+ const t = e.debug ? (o, n) => (console.log(`[@stonecrop/graphql-middleware] ${n.text}`, n.values ?? []), o.query(n)) : (o, n) => o.query(n);
278
+ return ye((o) => {
279
+ const n = o.input?.pgRegistry?.pgExecutors, r = n ? Object.values(n)[0] : void 0;
280
+ if (!r)
228
281
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
229
- return {
230
- typeDefs: kt,
282
+ return e.actionHandlers && Me(e.actionHandlers), Ae(), {
283
+ typeDefs: ve,
231
284
  objects: {
232
285
  Query: {
233
286
  plans: {
234
- stonecropMeta(l, { $doctype: f }) {
235
- return dt(f, (y) => T(String(y)) ?? null);
287
+ stonecropMeta(i, { $doctype: l }) {
288
+ return pe(l, (d) => M(String(d)) ?? null);
236
289
  },
237
290
  stonecropAllMeta() {
238
- return ut(wt());
291
+ return ge(oe());
239
292
  },
240
- stonecropRecord(l, { $doctype: f, $id: y, $options: M }) {
241
- return X(
242
- s,
243
- q({ doctype: f, id: y, options: M }),
244
- async (k, u) => {
245
- const S = /* @__PURE__ */ new Map();
246
- for (let r = 0; r < u.length; r++) {
247
- const p = String(u[r].doctype);
248
- S.has(p) || S.set(p, []), S.get(p).push(r);
293
+ stonecropRecord(i, { $doctype: l, $id: d, $options: S }) {
294
+ return Z(
295
+ r,
296
+ _({ doctype: l, id: d, options: S }),
297
+ async (h, a) => {
298
+ const $ = /* @__PURE__ */ new Map();
299
+ for (let y = 0; y < a.length; y++) {
300
+ const s = String(a[y].doctype);
301
+ $.has(s) || $.set(s, []), $.get(s).push(y);
249
302
  }
250
- const h = Array.from({ length: u.length });
251
- for (const [r, p] of S) {
252
- const a = T(r);
253
- if (!a) {
254
- for (const d of p) h[d] = { data: null, doctype: r };
255
- continue;
256
- }
257
- const R = Q(a);
258
- if (!R) {
259
- for (const d of p) h[d] = { data: null, doctype: r };
303
+ const R = Array.from({ length: a.length });
304
+ for (const [y, s] of $) {
305
+ const f = M(y);
306
+ if (!f) {
307
+ for (const w of s) R[w] = { data: null, doctype: y };
260
308
  continue;
261
309
  }
262
- const b = A(R.fieldname), c = U(a), F = p.map((d) => String(u[d].id)), { rows: W } = await e(k, {
263
- text: `SELECT ${c} FROM ${C(a.name, t.tables)} WHERE "${b}"::text = ANY($1::text[])`,
264
- values: [F]
265
- }), P = new Map(W.map((d) => [String(d[R.fieldname]), d]));
266
- for (const d of p) {
267
- const B = String(u[d].id), N = P.get(B);
268
- if (!N) {
269
- h[d] = { data: null, doctype: r };
310
+ const g = Q(f);
311
+ if (!g) throw V(y);
312
+ const T = D(g.fieldname), F = U(f), c = s.map((w) => String(a[w].id)), { rows: b } = await t(h, {
313
+ text: `SELECT ${F} FROM ${B(f.name, e.tables)} WHERE "${T}"::text = ANY($1::text[])`,
314
+ values: [c]
315
+ }), k = new Map(b.map((w) => [String(w[g.fieldname]), w]));
316
+ if (b.length !== k.size)
317
+ throw new Error(
318
+ `Doctype "${y}" declares "${g.fieldname}" as its identity, but that column is not unique in ${B(f.name, e.tables)} — ${b.length} rows matched ${k.size} distinct values, so a lookup cannot say which record it means. Declare a field that uniquely identifies a record, or add a unique constraint.`
319
+ );
320
+ for (const w of s) {
321
+ const A = String(a[w].id), I = k.get(A);
322
+ if (!I) {
323
+ R[w] = { data: null, doctype: y };
270
324
  continue;
271
325
  }
272
- const i = { ...N }, g = u[d].options ?? {}, v = g.includeNested === !0, m = Array.isArray(g.includeNested) ? new Set(g.includeNested) : null;
273
- if (a.links)
274
- for (const [$, E] of Object.entries(a.links)) {
275
- const D = E.fetch, J = E.cardinality === "noneOrMany" || E.cardinality === "atLeastOne", H = D?.method ?? (J ? "sync" : "lazy"), Y = D?.method === "sync" ? D.limit : J ? 50 : void 0;
276
- if (!(v || (m ? m.has($) : H === "sync"))) continue;
277
- if (H === "custom" && D?.method === "custom") {
278
- const x = D.handler, O = ht(x);
279
- O && (i[$] = await O(k, i, E));
326
+ const E = { ...I }, j = a[w].options ?? {}, H = j.includeNested === !0, O = Array.isArray(j.includeNested) ? new Set(j.includeNested) : null;
327
+ if (f.links)
328
+ for (const [u, m] of Object.entries(f.links)) {
329
+ const v = m.fetch, N = m.cardinality === "noneOrMany" || m.cardinality === "atLeastOne", W = v?.method ?? (N ? "sync" : "lazy"), Y = v?.method === "sync" ? v.limit : N ? 50 : void 0;
330
+ if (!(H || (O ? O.has(u) : W === "sync"))) continue;
331
+ if (W === "custom" && v?.method === "custom") {
332
+ const P = v.handler, x = Ee(P);
333
+ x && (E[u] = await x(h, E, m));
280
334
  continue;
281
335
  }
282
- if (H !== "sync" && !m?.has($)) continue;
283
- const L = T(E.target);
336
+ if (W !== "sync" && !O?.has(u)) continue;
337
+ const L = M(m.target);
284
338
  if (!L) continue;
285
- const z = U(L);
286
- if (J) {
287
- if (!E.backlink) continue;
288
- const x = A(E.backlink);
289
- let O = `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${x}"::text = $1`;
290
- const j = [B];
291
- Y != null && (O += " LIMIT $2", j.push(Y));
292
- const { rows: _ } = await e(k, {
293
- text: O,
294
- values: j
339
+ const X = U(L);
340
+ if (N) {
341
+ if (!m.backlink) continue;
342
+ const P = D(m.backlink);
343
+ let x = `SELECT ${X} FROM ${B(L.name, e.tables)} WHERE "${P}"::text = $1`;
344
+ const q = [A];
345
+ Y != null && (x += " LIMIT $2", q.push(Y));
346
+ const { rows: J } = await t(h, {
347
+ text: x,
348
+ values: q
295
349
  });
296
- i[$] = _;
350
+ E[u] = J;
297
351
  } else {
298
- if (!E.fieldname) continue;
299
- const x = i[E.fieldname];
300
- if (x == null) {
301
- i[$] = null;
352
+ if (!m.fieldname) continue;
353
+ const P = E[m.fieldname];
354
+ if (P == null) {
355
+ E[u] = null;
302
356
  continue;
303
357
  }
304
- const O = Q(L);
305
- if (!O) continue;
306
- const j = A(O.fieldname), { rows: _ } = await e(k, {
307
- text: `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${j}" = $1`,
308
- values: [x]
358
+ const x = Q(L);
359
+ if (!x) throw V(L.name);
360
+ const q = D(x.fieldname), { rows: J } = await t(h, {
361
+ text: `SELECT ${X} FROM ${B(L.name, e.tables)} WHERE "${q}" = $1`,
362
+ values: [P]
309
363
  });
310
- i[$] = _[0] ?? null;
364
+ E[u] = J[0] ?? null;
311
365
  }
312
366
  }
313
- const I = m && a.links ? [...m].filter(($) => !($ in a.links)) : void 0;
314
- h[d] = {
315
- data: i,
316
- doctype: r,
317
- unknownLinks: I?.length ? I : void 0
367
+ const p = O && f.links ? [...O].filter((u) => !(u in f.links)) : void 0;
368
+ R[w] = {
369
+ data: E,
370
+ doctype: y,
371
+ unknownLinks: p?.length ? p : void 0
318
372
  };
319
373
  }
320
374
  }
321
- return h;
375
+ return R;
322
376
  }
323
377
  );
324
378
  },
325
- stonecropRecords(l, { $doctype: f, $filters: y, $orderBy: M, $limit: k, $offset: u }) {
326
- return X(
327
- s,
328
- q({
329
- doctype: f,
330
- filters: y,
331
- orderBy: M,
332
- limit: k,
333
- offset: u
379
+ stonecropRecords(i, { $doctype: l, $filters: d, $orderBy: S, $limit: h, $offset: a, $includeTotal: $ }) {
380
+ return Z(
381
+ r,
382
+ _({
383
+ doctype: l,
384
+ filters: d,
385
+ orderBy: S,
386
+ limit: h,
387
+ offset: a,
388
+ includeTotal: $
334
389
  }),
335
- async (S, h) => await Promise.all(
336
- h.map(async (r) => {
337
- const p = String(r.doctype), a = T(p);
338
- if (!a)
339
- return { data: [], doctype: p, count: 0 };
340
- const R = new Set(K(a.fields).map((i) => i.fieldname)), b = U(a), c = [], F = [];
341
- if (r.filters != null)
342
- for (const [i, g] of Object.entries(r.filters)) {
343
- if (!R.has(i))
344
- throw new Error(`Unknown filter field: ${i} for doctype ${a.name}`);
345
- c.push(g), F.push(`"${A(i)}" = $${c.length}`);
390
+ async (R, y) => await Promise.all(
391
+ y.map(async (s) => {
392
+ const f = String(s.doctype), g = M(f);
393
+ if (!g)
394
+ return { data: [], doctype: f, hasMore: !1, count: s.includeTotal === !0 ? 0 : null };
395
+ const T = new Set(z(g.fields).map((p) => p.fieldname)), F = U(g), c = [], b = [];
396
+ if (s.filters != null)
397
+ for (const [p, u] of Object.entries(s.filters)) {
398
+ if (!T.has(p))
399
+ throw new Error(`Unknown filter field: ${p} for doctype ${g.name}`);
400
+ c.push(u), b.push(`"${D(p)}" = $${c.length}`);
346
401
  }
347
- const W = F.length > 0 ? ` WHERE ${F.join(" AND ")}` : "";
348
- let P = "";
349
- if (r.orderBy != null) {
350
- if (typeof r.orderBy != "string")
351
- throw new Error(`Invalid orderBy: expected string, got ${typeof r.orderBy}`);
352
- const i = r.orderBy, g = i.lastIndexOf("_");
353
- if (g <= 0)
354
- throw new Error(`Invalid orderBy format: "${i}". Expected FIELD_ASC or FIELD_DESC`);
355
- const v = i.slice(g + 1).toUpperCase();
356
- if (v !== "ASC" && v !== "DESC")
357
- throw new Error(`Invalid orderBy direction: "${v}". Must be ASC or DESC`);
358
- const m = i.slice(0, g);
359
- if (!R.has(m))
360
- throw new Error(`Unknown orderBy field: "${m}" for doctype ${a.name}`);
361
- P = ` ORDER BY "${A(m)}" ${v}`;
402
+ const k = b.length > 0 ? ` WHERE ${b.join(" AND ")}` : "";
403
+ let w = "";
404
+ if (s.orderBy != null) {
405
+ if (typeof s.orderBy != "string")
406
+ throw new Error(`Invalid orderBy: expected string, got ${typeof s.orderBy}`);
407
+ const p = s.orderBy, u = p.lastIndexOf("_");
408
+ if (u <= 0)
409
+ throw new Error(`Invalid orderBy format: "${p}". Expected FIELD_ASC or FIELD_DESC`);
410
+ const m = p.slice(u + 1).toUpperCase();
411
+ if (m !== "ASC" && m !== "DESC")
412
+ throw new Error(`Invalid orderBy direction: "${m}". Must be ASC or DESC`);
413
+ const v = p.slice(0, u);
414
+ if (!T.has(v))
415
+ throw new Error(`Unknown orderBy field: "${v}" for doctype ${g.name}`);
416
+ w = ` ORDER BY "${D(v)}" ${m}`;
362
417
  }
363
- let d = "";
364
- r.limit != null && (c.push(r.limit), d += ` LIMIT $${c.length}`), r.offset != null && (c.push(r.offset), d += ` OFFSET $${c.length}`);
365
- const { rows: B } = await e(S, {
366
- text: `SELECT ${b} FROM ${C(a.name, t.tables)}${W}${P}${d}`,
418
+ if (s.limit != null && typeof s.limit != "number")
419
+ throw new Error(`Invalid limit: expected number, got ${typeof s.limit}`);
420
+ const A = s.limit ?? (e.defaultRecordLimit === void 0 ? 200 : e.defaultRecordLimit);
421
+ let I = "";
422
+ A != null && (c.push(A + 1), I += ` LIMIT $${c.length}`), s.offset != null && (c.push(s.offset), I += ` OFFSET $${c.length}`);
423
+ const { rows: E } = await t(R, {
424
+ text: `SELECT ${F} FROM ${B(g.name, e.tables)}${k}${w}${I}`,
367
425
  values: c
368
- });
369
- let N = B.length;
370
- if (r.limit != null || r.offset != null) {
371
- const i = [], g = [];
372
- if (r.filters != null)
373
- for (const [I, $] of Object.entries(r.filters))
374
- R.has(I) && (i.push($), g.push(`"${A(I)}" = $${i.length}`));
375
- const v = g.length > 0 ? ` WHERE ${g.join(" AND ")}` : "", { rows: m } = await e(S, {
376
- text: `SELECT COUNT(*) AS row_count FROM ${C(a.name, t.tables)}${v}`,
377
- values: i
426
+ }), j = A != null && E.length > A, H = j ? E.slice(0, A ?? E.length) : E;
427
+ let O = null;
428
+ if (s.includeTotal === !0) {
429
+ const p = [], u = [];
430
+ if (s.filters != null)
431
+ for (const [N, W] of Object.entries(s.filters))
432
+ T.has(N) && (p.push(W), u.push(`"${D(N)}" = $${p.length}`));
433
+ const m = u.length > 0 ? ` WHERE ${u.join(" AND ")}` : "", { rows: v } = await t(R, {
434
+ text: `SELECT COUNT(*) AS row_count FROM ${B(g.name, e.tables)}${m}`,
435
+ values: p
378
436
  });
379
- N = parseInt(m[0]?.row_count ?? "0", 10);
437
+ O = parseInt(v[0]?.row_count ?? "0", 10);
380
438
  }
381
- return { data: B, doctype: p, count: N };
439
+ return { data: H, doctype: f, hasMore: j, count: O };
382
440
  })
383
441
  )
384
442
  );
@@ -387,52 +445,63 @@ const kt = ft`
387
445
  },
388
446
  Mutation: {
389
447
  plans: {
390
- stonecropAction(l, { $doctype: f, $action: y, $args: M }) {
391
- return lt(
392
- s,
393
- q({ doctype: f, action: y, actionArgs: M }),
394
- async (k, u) => {
395
- const S = T(String(u.doctype));
396
- if (!S)
397
- return {
398
- success: !1,
399
- data: null,
400
- error: `Unknown doctype: ${u.doctype}`
401
- };
402
- const h = S.workflow?.actions?.[u.action];
403
- if (!h)
448
+ stonecropAction(i, { $doctype: l, $action: d, $args: S }) {
449
+ return fe(
450
+ r,
451
+ _({ doctype: l, action: d, actionArgs: S }),
452
+ async (h, a) => {
453
+ const $ = M(String(a.doctype));
454
+ if (!$)
404
455
  return {
405
456
  success: !1,
406
457
  data: null,
407
- error: `Unknown action: ${u.action} on ${u.doctype}`
458
+ error: `Unknown doctype: ${a.doctype}`
408
459
  };
409
- const r = Q(S);
410
- if (!r)
460
+ const R = $.workflow?.actions?.[a.action];
461
+ if (!R)
411
462
  return {
412
463
  success: !1,
413
464
  data: null,
414
- error: `No primary key for doctype: ${u.doctype}`
465
+ error: `Unknown action: ${a.action} on ${a.doctype}`
415
466
  };
416
- const p = A(r.fieldname), a = C(S.name, t.tables), b = (Array.isArray(u.actionArgs) ? u.actionArgs : [])[0]?.id;
467
+ const y = B($.name, e.tables), s = () => {
468
+ const c = Q($);
469
+ if (!c) throw V(String(a.doctype));
470
+ return D(c.fieldname);
471
+ }, f = Array.isArray(a.actionArgs) ? a.actionArgs : [], g = f[0]?.id, T = f[0]?.data ?? {}, F = e.actionHandlers?.[$.name]?.[String(a.action)];
417
472
  try {
418
- return await $t(h, {
419
- readState: async () => {
420
- if (b == null) return;
421
- const { rows: c } = await e(k, {
422
- text: `SELECT "status" FROM ${a} WHERE "${p}"::text = $1`,
423
- values: [String(b)]
424
- });
425
- return c[0]?.status == null ? void 0 : c[0].status;
426
- },
427
- writeState: async (c) => {
428
- await e(k, {
429
- text: `UPDATE ${a} SET "status" = $1 WHERE "${p}"::text = $2`,
430
- values: [c, String(b)]
431
- });
432
- }
473
+ return await h.withTransaction(async (c) => {
474
+ const b = await be(R, {
475
+ readState: async () => {
476
+ if (g == null) return null;
477
+ const { rows: k } = await t(c, {
478
+ text: `SELECT "status" FROM ${y} WHERE "${s()}"::text = $1 FOR UPDATE`,
479
+ values: [String(g)]
480
+ });
481
+ return k.length === 0 ? null : k[0].status ?? void 0;
482
+ },
483
+ writeState: async (k) => {
484
+ await t(c, {
485
+ text: `UPDATE ${y} SET "status" = $1 WHERE "${s()}"::text = $2`,
486
+ values: [k, String(g)]
487
+ });
488
+ },
489
+ runEffect: F ? (k) => F({
490
+ pgClient: c,
491
+ doctype: String(a.doctype),
492
+ action: String(a.action),
493
+ meta: $,
494
+ recordId: g,
495
+ data: T,
496
+ args: f,
497
+ currentState: k
498
+ }) : void 0
499
+ });
500
+ if (!b.success) throw new ee(b);
501
+ return b;
433
502
  });
434
503
  } catch (c) {
435
- return {
504
+ return c instanceof ee ? c.outcome : {
436
505
  success: !1,
437
506
  data: null,
438
507
  error: c instanceof Error ? c.message : String(c)
@@ -447,48 +516,96 @@ const kt = ft`
447
516
  };
448
517
  });
449
518
  };
450
- function K(t) {
451
- const e = [];
452
- for (const o of t)
453
- o.kind === "fieldset" ? e.push(...K(o.schema)) : e.push(o);
454
- return e;
519
+ function z(e) {
520
+ const t = [];
521
+ for (const o of e)
522
+ o.kind === "fieldset" ? t.push(...z(o.schema)) : t.push(o);
523
+ return t;
455
524
  }
456
- function Et(t, e) {
525
+ function Re(e, t) {
457
526
  const o = [];
458
- for (const n of K(t)) {
527
+ for (const n of z(e)) {
459
528
  if (n.kind !== "field" || n.computed) continue;
460
- const s = e.get(n.fieldname);
461
- if (s && ct(s, n.component) !== "inline") continue;
462
- const l = A(n.fieldname);
463
- o.push(l !== n.fieldname ? `"${l}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
529
+ const r = t.get(n.fieldname);
530
+ if (r && ue(r, n.component) !== "inline") continue;
531
+ const i = D(n.fieldname);
532
+ o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
464
533
  }
465
534
  return o;
466
535
  }
467
- function U(t) {
468
- const e = /* @__PURE__ */ new Map();
469
- if (t.links)
470
- for (const [o, n] of Object.entries(t.links))
471
- e.set(n.fieldname ?? o, n);
472
- return Et(t.fields, e).join(", ");
536
+ function U(e) {
537
+ const t = /* @__PURE__ */ new Map();
538
+ if (e.links)
539
+ for (const [o, n] of Object.entries(e.links))
540
+ t.set(n.fieldname ?? o, n);
541
+ return Re(e.fields, t).join(", ");
542
+ }
543
+ function Q(e) {
544
+ const t = de(e.fields);
545
+ return e.fields.find((o) => o.kind === "field" && o.fieldname === t);
546
+ }
547
+ function Me(e) {
548
+ const t = Object.entries(e);
549
+ if (t.length === 0) return;
550
+ if (oe().length === 0) {
551
+ console.warn(
552
+ "[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the `actionHandlers` map could not be verified. Load doctypes before building the schema to have stale handler keys reported."
553
+ );
554
+ return;
555
+ }
556
+ const o = [];
557
+ for (const [n, r] of t) {
558
+ const i = M(n);
559
+ if (!i) {
560
+ o.push(`"${n}": no doctype by that name is registered`);
561
+ continue;
562
+ }
563
+ if (i.name !== n) {
564
+ o.push(
565
+ `"${n}": matches the doctype named "${i.name}" by slug, but handlers are looked up by name — key it "${i.name}"`
566
+ );
567
+ continue;
568
+ }
569
+ const l = i.workflow?.actions ?? {};
570
+ for (const d of Object.keys(r))
571
+ d in l || o.push(`"${n}.${d}": the doctype declares no action by that key`);
572
+ }
573
+ if (o.length > 0)
574
+ throw new Error(
575
+ `StonecropPlugin: ${o.length} registered action handler${o.length === 1 ? "" : "s"} cannot be reached and would never run:
576
+ ${o.join(`
577
+ `)}`
578
+ );
579
+ }
580
+ function Ae() {
581
+ const e = ke();
582
+ if (e.length !== 0)
583
+ throw new Error(
584
+ `StonecropPlugin: ${e.length} doctype reference${e.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
585
+ ` + e.map((t) => `${t.path.join(".")}: ${t.message}`).join(`
586
+ `)
587
+ );
473
588
  }
474
- function Q(t) {
475
- return it(t.fields);
589
+ function V(e) {
590
+ return new Error(
591
+ `Doctype "${e}" has no identity field: it declares no field with \`primaryKey: true\` and no field named \`id\`. Declare one of the two — records cannot be fetched or acted on until then.`
592
+ );
476
593
  }
477
- function C(t, e) {
478
- const o = e?.[t] ?? at(t), n = o.indexOf(".");
594
+ function B(e, t) {
595
+ const o = t?.[e] ?? le(e), n = o.indexOf(".");
479
596
  return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
480
597
  }
481
- const Wt = (t = {}) => {
482
- const { logPlans: e = !0, logTiming: o = !1 } = t, n = (s, l) => ({
483
- plan: (f) => {
484
- e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${s}.${l}`);
485
- const y = o ? Date.now() : 0, M = f();
598
+ const _e = (e = {}) => {
599
+ const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
600
+ plan: (l) => {
601
+ t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
602
+ const d = o ? Date.now() : 0, S = l();
486
603
  return o && console.log(
487
- `[@stonecrop/graphql-middleware] Plan built for ${s}.${l} in ${Date.now() - y}ms`
488
- ), M;
604
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - d}ms`
605
+ ), S;
489
606
  }
490
607
  });
491
- return gt({
608
+ return me({
492
609
  Query: {
493
610
  stonecropRecord: n("Query", "stonecropRecord"),
494
611
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -499,38 +616,37 @@ const Wt = (t = {}) => {
499
616
  stonecropAction: n("Mutation", "stonecropAction")
500
617
  }
501
618
  });
502
- }, Mt = {
619
+ }, Oe = {
503
620
  name: "StonecropFieldCasingPlugin",
504
621
  version: "0.0.0",
505
622
  inflection: {
506
623
  replace: {
507
- attribute(t, e, o) {
624
+ attribute(e, t, o) {
508
625
  return this.upperCamelCase(this._attributeName(o));
509
626
  }
510
627
  }
511
628
  }
512
- }, Rt = (t) => ({
513
- extends: [yt],
514
- plugins: t?.fieldCasing === "pascal" ? [Mt] : []
515
- }), Jt = Rt();
629
+ }, xe = (e) => ({
630
+ extends: [we],
631
+ plugins: e?.fieldCasing === "pascal" ? [Oe] : []
632
+ }), Ue = xe();
516
633
  export {
517
- V as DoctypeValidationError,
518
- Jt as StonecropPreset,
519
- $t as applyGuardedTransition,
520
- Pt as clearFetchHandlers,
521
- Dt as clearRegistry,
522
- Wt as createDebugPlugin,
523
- jt as createStonecropPlugin,
524
- Rt as createStonecropPreset,
525
- wt as getAllMeta,
526
- ht as getFetchHandler,
527
- T as getMeta,
528
- It as hasMeta,
529
- St as loadDoctypes,
530
- Nt as loadDoctypesFromObject,
531
- qt as makePgService,
532
- Tt as registerFetchHandler,
533
- kt as typeDefs,
534
- Lt as validateReferences
634
+ G as DoctypeValidationError,
635
+ Ue as StonecropPreset,
636
+ be as applyGuardedTransition,
637
+ He as clearFetchHandlers,
638
+ We as clearRegistry,
639
+ _e as createDebugPlugin,
640
+ Je as createStonecropPlugin,
641
+ xe as createStonecropPreset,
642
+ oe as getAllMeta,
643
+ Ee as getFetchHandler,
644
+ M as getMeta,
645
+ Pe as hasMeta,
646
+ Se as loadDoctypes,
647
+ Le as loadDoctypesFromObject,
648
+ Ge as makePgService,
649
+ qe as registerFetchHandler,
650
+ ve as typeDefs
535
651
  };
536
652
  //# sourceMappingURL=index.js.map