@stonecrop/graphql-middleware 0.16.6 → 0.18.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,15 +1,24 @@
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 {
1
+ import { readdirSync as ge, statSync as me, readFileSync as ye } from "node:fs";
2
+ import { join as we } from "node:path";
3
+ import { validateDoctype as ue, parseDoctype as fe, isActionAllowedInState as Se, camelToSnake as A, resolveLinkRenderMode as oe, pascalToSnake as $e, getRecordIdField as ke } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as Ee, loadOneWithPgClient as ce } from "@dataplan/pg";
5
+ import { object as ee, constant as be, lambda as ve } from "postgraphile/grafast";
6
+ import { gql as Re, extendSchema as Ae, wrapPlans as Me } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as Oe } from "postgraphile/presets/amber";
8
+ import { makePgService as rt } from "postgraphile/adaptors/pg";
9
+ function V(t) {
10
+ const e = [];
11
+ for (const o of t)
12
+ o.kind === "fieldset" ? e.push(...V(o.schema)) : e.push(o);
13
+ return e;
14
+ }
15
+ function X(t) {
16
+ return V(t).filter((e) => e.kind === "field" && !e.computed);
17
+ }
18
+ const P = /* @__PURE__ */ new Map();
19
+ class re extends Error {
11
20
  constructor(e, o) {
12
- const n = o.map((s) => ` ${s.path.join(".")}: ${s.message}`).join(`
21
+ const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
13
22
  `);
14
23
  super(`Invalid doctype definition in ${e}:
15
24
  ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
@@ -17,126 +26,184 @@ ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
17
26
  file;
18
27
  errors;
19
28
  }
20
- function St(t, e = {}) {
21
- const o = et(t);
29
+ function xe(t, e = {}) {
30
+ const o = ge(t);
22
31
  for (const n of o) {
23
- const s = rt(t, n);
24
- nt(s).isDirectory() ? St(s, e) : n.endsWith(".json") && mt(s, e);
32
+ const r = we(t, n);
33
+ me(r).isDirectory() ? xe(r, e) : n.endsWith(".json") && Te(r, e);
25
34
  }
26
35
  }
27
- function mt(t, e) {
28
- const o = ot(t, "utf-8");
36
+ function Te(t, e) {
37
+ const o = ye(t, "utf-8");
29
38
  let n;
30
39
  try {
31
40
  n = JSON.parse(o);
32
- } catch (f) {
33
- const y = {
41
+ } catch (l) {
42
+ const d = {
34
43
  path: [],
35
- message: `Invalid JSON: ${f instanceof Error ? f.message : String(f)}`
44
+ message: `Invalid JSON: ${l instanceof Error ? l.message : String(l)}`
36
45
  };
37
46
  if (e.continueOnError) {
38
- e.onError?.(t, [y]);
47
+ e.onError?.(t, [d]);
39
48
  return;
40
49
  }
41
- throw new V(t, [y]);
50
+ throw new re(t, [d]);
42
51
  }
43
- const s = Z(n);
44
- if (!s.success) {
52
+ const r = ue(n);
53
+ if (!r.success) {
45
54
  if (e.continueOnError) {
46
- e.onError?.(t, s.errors);
55
+ e.onError?.(t, r.errors);
47
56
  return;
48
57
  }
49
- throw new V(t, s.errors);
58
+ throw new re(t, r.errors);
50
59
  }
51
- const l = tt(n);
52
- w.set(l.name, l);
60
+ const i = fe(n);
61
+ P.set(i.name, i);
53
62
  }
54
- function Nt(t, e = {}) {
63
+ function Qe(t, e = {}) {
55
64
  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) {
65
+ const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ue(r);
66
+ if (!i.success) {
58
67
  if (e.continueOnError) {
59
- e.onError?.(o, l.errors);
68
+ e.onError?.(o, i.errors);
60
69
  continue;
61
70
  }
62
- throw new V(o, l.errors);
71
+ throw new re(o, i.errors);
63
72
  }
64
- const f = tt(s);
65
- w.set(f.name, f);
73
+ const l = fe(r);
74
+ P.set(l.name, l);
66
75
  }
67
76
  }
68
- function T(t) {
69
- const e = w.get(t);
77
+ function I(t) {
78
+ const e = P.get(t);
70
79
  if (e) return e;
71
- for (const o of w.values())
80
+ for (const o of P.values())
72
81
  if (o.slug === t) return o;
73
82
  }
74
- function wt() {
75
- return Array.from(w.values());
83
+ function he() {
84
+ return Array.from(P.values());
76
85
  }
77
- function It(t) {
78
- return w.has(t);
86
+ function Ve(t) {
87
+ return P.has(t);
79
88
  }
80
- function Dt() {
81
- w.clear();
89
+ function ze() {
90
+ P.clear();
82
91
  }
83
- function Lt() {
92
+ function Le() {
84
93
  const t = [];
85
- for (const e of w.values()) {
86
- e.inherits && !w.has(e.inherits) && t.push({
94
+ for (const e of P.values()) {
95
+ e.inherits && I(e.inherits) === void 0 && t.push({
87
96
  path: [e.name, "inherits"],
88
97
  message: `References unknown doctype: ${e.inherits}`
89
98
  });
90
- for (const o of e.fields) {
91
- if (o.kind !== "field") continue;
92
- const n = o.doctype;
93
- n !== void 0 && !w.has(n) && t.push({
94
- path: [e.name, "fields", o.fieldname, "doctype"],
95
- message: `Link references unknown doctype: ${n}`
99
+ const o = V(e.fields);
100
+ for (const n of o) {
101
+ if (n.kind !== "field") continue;
102
+ const r = n.doctype;
103
+ r !== void 0 && I(r) === void 0 && t.push({
104
+ path: [e.name, "fields", n.fieldname, "doctype"],
105
+ message: `Link references unknown doctype: ${r}`
96
106
  });
97
107
  }
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"],
102
- message: `Link references unknown doctype: ${n.target}`
108
+ if (e.links) {
109
+ const n = new Set(o.map((i) => i.fieldname)), r = new Set(X(e.fields).map((i) => i.fieldname));
110
+ for (const [i, l] of Object.entries(e.links)) {
111
+ if (I(l.target) === void 0 && t.push({
112
+ path: [e.name, "links", i, "target"],
113
+ message: `Link references unknown doctype: ${l.target}`
114
+ }), l.fetch?.method === "custom") continue;
115
+ if (l.cardinality === "noneOrMany" || l.cardinality === "atLeastOne") {
116
+ l.backlink || t.push({
117
+ path: [e.name, "links", i, "backlink"],
118
+ message: `Link "${i}" is ${l.cardinality} but names no \`backlink\`, so the runtime cannot find the target rows and drops the link with no error. Name the field on "${l.target}" that points back to this doctype.`
119
+ });
120
+ continue;
121
+ }
122
+ const d = l.fieldname ?? i;
123
+ r.has(d) || t.push({
124
+ // Point at whichever half actually carries the binding: the `fieldname`
125
+ // property when it is set, otherwise the key itself. Naming `target` here
126
+ // would send the reader to the one part that resolved correctly.
127
+ path: l.fieldname ? [e.name, "links", i, "fieldname"] : [e.name, "links", i],
128
+ // Two different repairs, so two different diagnoses: a name nothing declares
129
+ // is a typo, while a name that resolves to a column-less field is a binding
130
+ // pointed at the wrong one of several real fields.
131
+ message: n.has(d) ? `Link "${i}" binds to field "${d}", which has no database column of its own — it is computed, or a container rather than a value — so there is no foreign key to read and the record read fails on the missing column. Bind the link to the field holding the foreign key.` : `Link "${i}" binds to field "${d}", which this doctype does not declare, so it resolves to null with no error. Declare that field, or set \`fieldname\` to the field holding the foreign key. (A link's key is its fieldname unless \`fieldname\` overrides it.)`
103
132
  });
133
+ }
134
+ }
104
135
  }
105
136
  return t;
106
137
  }
107
- const G = /* @__PURE__ */ new Map();
108
- function Tt(t, e) {
109
- G.set(t, e);
138
+ const ie = /* @__PURE__ */ new Map();
139
+ function Ye(t, e) {
140
+ ie.set(t, e);
110
141
  }
111
- function ht(t) {
112
- return G.get(t);
142
+ function Ne(t) {
143
+ return ie.get(t);
113
144
  }
114
- function Pt() {
115
- G.clear();
145
+ function Xe() {
146
+ ie.clear();
116
147
  }
117
- async function $t(t, e, o) {
118
- if (!t.selfTransition && t.nextState == null)
148
+ async function De(t, e, o) {
149
+ const n = t.label ?? "unknown", r = t.selfTransition === !0, i = r || t.nextState != null;
150
+ if (!i && !e.runEffect)
119
151
  return {
120
152
  success: !1,
121
153
  data: null,
122
- error: `Action "${t.label ?? "unknown"}" has no workflow transition and no server-side effect is wired — nothing was executed.`
154
+ 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
155
  };
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), {
156
+ if (r && !e.writeData && !e.runEffect)
157
+ return {
158
+ success: !1,
159
+ data: null,
160
+ error: `Action "${n}" persists record data in place, which this backend does not support.`
161
+ };
162
+ const l = (t.allowedStates?.length ?? 0) > 0;
163
+ let d;
164
+ if (l || i) {
165
+ const v = await e.readState();
166
+ if (v === null) {
167
+ if (r && e.writeData) {
168
+ const R = await e.writeData(o ?? {}, !1);
169
+ return !R || Object.keys(R).length === 0 ? {
170
+ success: !1,
171
+ data: null,
172
+ error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
173
+ } : { success: !0, data: R, error: null };
174
+ }
175
+ return {
176
+ success: !1,
177
+ data: null,
178
+ error: `Action "${n}" targets a record that does not exist — nothing was executed.`
179
+ };
180
+ }
181
+ d = v ?? "";
182
+ }
183
+ if (!Se(t, d ?? ""))
184
+ return {
185
+ success: !1,
186
+ data: null,
187
+ error: `Action not allowed from state: ${d || "(unknown)"}`
188
+ };
189
+ let b;
190
+ if (e.runEffect)
191
+ try {
192
+ b = await e.runEffect(d);
193
+ } catch (v) {
194
+ return {
195
+ success: !1,
196
+ data: null,
197
+ error: `Action "${n}" failed: ${v instanceof Error ? v.message : String(v)}`
198
+ };
199
+ }
200
+ return r ? { success: !0, data: (e.writeData ? await e.writeData(o ?? {}, !0) : b) ?? null, error: null } : t.nextState == null ? { success: !0, data: b ?? null, error: null } : (await e.writeState(t.nextState), {
130
201
  success: !0,
131
- data: { state: t.nextState },
202
+ data: b ?? { state: t.nextState },
132
203
  error: null
133
- }) : {
134
- success: !1,
135
- data: null,
136
- error: `Action not allowed from state: ${n || "(unknown)"}`
137
- };
204
+ });
138
205
  }
139
- const kt = ft`
206
+ const Fe = Re`
140
207
  type StonecropFieldMeta {
141
208
  kind: String!
142
209
  fieldname: String!
@@ -189,18 +256,42 @@ const kt = ft`
189
256
  data: JSON
190
257
  doctype: String!
191
258
  unknownLinks: [String!]
259
+ """
260
+ Fields whose linked rows were cut short by a row cap, so data holds a prefix of the
261
+ relation rather than all of it. Null when nothing was truncated. A link cannot be paged,
262
+ so a client that sees a name here must not write that relation back — the rows it never
263
+ received would be deleted.
264
+ """
265
+ truncatedLinks: [String!]
192
266
  }
193
267
 
194
268
  type StonecropRecordsResult {
195
269
  data: [JSON!]!
196
270
  doctype: String!
197
- count: Int!
271
+ """
272
+ Whether further records exist beyond this page. Always answered — it is read from the
273
+ page itself (one extra row is requested and discarded), so it costs no second query.
274
+ """
275
+ hasMore: Boolean!
276
+ """
277
+ Total matching the filters, ignoring limit/offset. Null unless the query asked for it
278
+ with includeTotal, because counting is a full scan on most backends.
279
+ """
280
+ count: Int
198
281
  }
199
282
 
200
283
  type StonecropActionResult {
201
284
  success: Boolean!
202
285
  data: JSON
203
286
  error: String
287
+ """
288
+ Keys the write discarded because the doctype declares no column for them, or because the
289
+ value was a nested relation rather than a column value. Null when everything sent was
290
+ stored. The action still succeeded — this is what it did not keep, and a client that
291
+ reports an unqualified success without checking it tells the user data was saved that
292
+ was not.
293
+ """
294
+ droppedFields: [String!]
204
295
  }
205
296
 
206
297
  extend type Query {
@@ -213,6 +304,7 @@ const kt = ft`
213
304
  orderBy: String
214
305
  limit: Int
215
306
  offset: Int
307
+ includeTotal: Boolean
216
308
  options: JSON
217
309
  ): StonecropRecordsResult
218
310
  }
@@ -220,165 +312,187 @@ const kt = ft`
220
312
  extend type Mutation {
221
313
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
222
314
  }
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)
315
+ `;
316
+ class le extends Error {
317
+ constructor(e) {
318
+ super(e.error ?? "Action failed"), this.outcome = e, this.name = "ActionRolledBack";
319
+ }
320
+ outcome;
321
+ }
322
+ const de = "__stonecropLinkFk_", Q = "status", Ze = (t = {}) => {
323
+ const e = t.debug ? (n, r) => (console.log(`[@stonecrop/graphql-middleware] ${r.text}`, r.values ?? []), n.query(r)) : (n, r) => n.query(r), o = t.defaultRecordLimit === void 0 ? 200 : t.defaultRecordLimit;
324
+ return Ae((n) => {
325
+ const r = n.input?.pgRegistry?.pgExecutors, i = r ? Object.values(r)[0] : void 0;
326
+ if (!i)
228
327
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
229
- return {
230
- typeDefs: kt,
328
+ return t.actionHandlers && Be(t.actionHandlers), je(), {
329
+ typeDefs: Fe,
231
330
  objects: {
232
331
  Query: {
233
332
  plans: {
234
- stonecropMeta(l, { $doctype: f }) {
235
- return dt(f, (y) => T(String(y)) ?? null);
333
+ stonecropMeta(l, { $doctype: d }) {
334
+ return ve(d, (b) => I(String(b)) ?? null);
236
335
  },
237
336
  stonecropAllMeta() {
238
- return ut(wt());
337
+ return be(he());
239
338
  },
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);
339
+ stonecropRecord(l, { $doctype: d, $id: b, $options: v }) {
340
+ return ce(
341
+ i,
342
+ ee({ doctype: d, id: b, options: v }),
343
+ async (R, h) => {
344
+ const w = /* @__PURE__ */ new Map();
345
+ for (let g = 0; g < h.length; g++) {
346
+ const c = String(h[g].doctype);
347
+ w.has(c) || w.set(c, []), w.get(c).push(g);
249
348
  }
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 };
349
+ const M = Array.from({ length: h.length });
350
+ for (const [g, c] of w) {
351
+ const m = I(g);
352
+ if (!m) {
353
+ for (const a of c) M[a] = { data: null, doctype: g };
255
354
  continue;
256
355
  }
257
- const R = Q(a);
258
- if (!R) {
259
- for (const d of p) h[d] = { data: null, doctype: r };
260
- continue;
356
+ const p = te(m);
357
+ if (!p) throw ne(g);
358
+ const B = A(p.fieldname), H = Y(m), O = c.map((a) => String(h[a].id)), D = new Map(V(m.fields).map((a) => [a.fieldname, a])), L = [];
359
+ for (const [a, f] of Object.entries(m.links ?? {})) {
360
+ if (f.cardinality === "noneOrMany" || f.cardinality === "atLeastOne") continue;
361
+ const y = f.fieldname ?? a;
362
+ oe(f, D.get(y)?.component) !== "inline" && L.push({ fieldname: y, alias: `${de}${y}` });
261
363
  }
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 };
364
+ const q = [
365
+ H,
366
+ ...L.map(({ fieldname: a, alias: f }) => `"${A(a)}" AS "${f}"`)
367
+ ].filter(Boolean).join(", "), { rows: s } = await e(R, {
368
+ text: `SELECT ${q} FROM ${W(m.name, t.tables)} WHERE "${B}"::text = ANY($1::text[])`,
369
+ values: [O]
370
+ }), $ = new Map(s.map((a) => [String(a[p.fieldname]), a]));
371
+ if (s.length !== $.size)
372
+ throw new Error(
373
+ `Doctype "${g}" declares "${p.fieldname}" as its identity, but that column is not unique in ${W(m.name, t.tables)} — ${s.length} rows matched ${$.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.`
374
+ );
375
+ for (const a of c) {
376
+ const f = String(h[a].id), y = $.get(f);
377
+ if (!y) {
378
+ M[a] = { data: null, doctype: g };
270
379
  continue;
271
380
  }
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));
381
+ const k = { ...y }, u = [], E = h[a].options ?? {}, N = E.includeNested === !0, S = Array.isArray(E.includeNested) ? new Set(E.includeNested) : null;
382
+ if (m.links)
383
+ for (const [x, T] of Object.entries(m.links)) {
384
+ const j = T.fieldname ?? x, J = T.fetch, Z = T.cardinality === "noneOrMany" || T.cardinality === "atLeastOne", se = J?.method ?? (Z ? "sync" : "lazy"), pe = J?.method === "sync" ? J.limit : void 0, G = Z ? pe ?? o : void 0;
385
+ if (!(N || (S ? S.has(x) : se === "sync"))) continue;
386
+ if (se === "custom" && J?.method === "custom") {
387
+ const _ = J.handler, C = Ne(_);
388
+ C && (k[j] = await C(R, k, T));
280
389
  continue;
281
390
  }
282
- if (H !== "sync" && !m?.has($)) continue;
283
- const L = T(E.target);
284
- 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
391
+ if (oe(T, D.get(j)?.component) === "inline") continue;
392
+ const U = I(T.target);
393
+ if (!U) continue;
394
+ const ae = Y(U);
395
+ if (Z) {
396
+ if (!T.backlink) continue;
397
+ const _ = A(T.backlink);
398
+ let C = `SELECT ${ae} FROM ${W(U.name, t.tables)} WHERE "${_}"::text = $1`;
399
+ const z = [f];
400
+ G != null && (C += " LIMIT $2", z.push(G + 1));
401
+ const { rows: K } = await e(R, {
402
+ text: C,
403
+ values: z
295
404
  });
296
- i[$] = _;
405
+ G != null && K.length > G ? (u.push(j), k[j] = K.slice(0, G)) : k[j] = K;
297
406
  } else {
298
- if (!E.fieldname) continue;
299
- const x = i[E.fieldname];
300
- if (x == null) {
301
- i[$] = null;
407
+ const _ = k[`${de}${j}`];
408
+ if (_ == null) {
409
+ k[j] = null;
302
410
  continue;
303
411
  }
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]
412
+ const C = te(U);
413
+ if (!C) throw ne(U.name);
414
+ const z = A(C.fieldname), { rows: K } = await e(R, {
415
+ text: `SELECT ${ae} FROM ${W(U.name, t.tables)} WHERE "${z}" = $1`,
416
+ values: [_]
309
417
  });
310
- i[$] = _[0] ?? null;
418
+ k[j] = K[0] ?? null;
311
419
  }
312
420
  }
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
421
+ for (const { alias: x } of L) delete k[x];
422
+ const F = S && m.links ? [...S].filter((x) => !(x in m.links)) : void 0;
423
+ M[a] = {
424
+ data: k,
425
+ doctype: g,
426
+ unknownLinks: F?.length ? F : void 0,
427
+ truncatedLinks: u.length ? u : void 0
318
428
  };
319
429
  }
320
430
  }
321
- return h;
431
+ return M;
322
432
  }
323
433
  );
324
434
  },
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
435
+ stonecropRecords(l, { $doctype: d, $filters: b, $orderBy: v, $limit: R, $offset: h, $includeTotal: w }) {
436
+ return ce(
437
+ i,
438
+ ee({
439
+ doctype: d,
440
+ filters: b,
441
+ orderBy: v,
442
+ limit: R,
443
+ offset: h,
444
+ includeTotal: w
334
445
  }),
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}`);
446
+ async (M, g) => await Promise.all(
447
+ g.map(async (c) => {
448
+ const m = String(c.doctype), p = I(m);
449
+ if (!p)
450
+ return { data: [], doctype: m, hasMore: !1, count: c.includeTotal === !0 ? 0 : null };
451
+ const B = new Set(V(p.fields).map((u) => u.fieldname)), H = Y(p), O = [], D = [];
452
+ if (c.filters != null)
453
+ for (const [u, E] of Object.entries(c.filters)) {
454
+ if (!B.has(u))
455
+ throw new Error(`Unknown filter field: ${u} for doctype ${p.name}`);
456
+ O.push(E), D.push(`"${A(u)}" = $${O.length}`);
346
457
  }
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}`;
458
+ const L = D.length > 0 ? ` WHERE ${D.join(" AND ")}` : "";
459
+ let q = "";
460
+ if (c.orderBy != null) {
461
+ if (typeof c.orderBy != "string")
462
+ throw new Error(`Invalid orderBy: expected string, got ${typeof c.orderBy}`);
463
+ const u = c.orderBy, E = u.lastIndexOf("_");
464
+ if (E <= 0)
465
+ throw new Error(`Invalid orderBy format: "${u}". Expected FIELD_ASC or FIELD_DESC`);
466
+ const N = u.slice(E + 1).toUpperCase();
467
+ if (N !== "ASC" && N !== "DESC")
468
+ throw new Error(`Invalid orderBy direction: "${N}". Must be ASC or DESC`);
469
+ const S = u.slice(0, E);
470
+ if (!B.has(S))
471
+ throw new Error(`Unknown orderBy field: "${S}" for doctype ${p.name}`);
472
+ q = ` ORDER BY "${A(S)}" ${N}`;
362
473
  }
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}`,
367
- 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
474
+ if (c.limit != null && typeof c.limit != "number")
475
+ throw new Error(`Invalid limit: expected number, got ${typeof c.limit}`);
476
+ const s = c.limit ?? o;
477
+ let $ = "";
478
+ s != null && (O.push(s + 1), $ += ` LIMIT $${O.length}`), c.offset != null && (O.push(c.offset), $ += ` OFFSET $${O.length}`);
479
+ const { rows: a } = await e(M, {
480
+ text: `SELECT ${H} FROM ${W(p.name, t.tables)}${L}${q}${$}`,
481
+ values: O
482
+ }), f = s != null && a.length > s, y = f ? a.slice(0, s ?? a.length) : a;
483
+ let k = null;
484
+ if (c.includeTotal === !0) {
485
+ const u = [], E = [];
486
+ if (c.filters != null)
487
+ for (const [F, x] of Object.entries(c.filters))
488
+ B.has(F) && (u.push(x), E.push(`"${A(F)}" = $${u.length}`));
489
+ const N = E.length > 0 ? ` WHERE ${E.join(" AND ")}` : "", { rows: S } = await e(M, {
490
+ text: `SELECT COUNT(*) AS row_count FROM ${W(p.name, t.tables)}${N}`,
491
+ values: u
378
492
  });
379
- N = parseInt(m[0]?.row_count ?? "0", 10);
493
+ k = parseInt(S[0]?.row_count ?? "0", 10);
380
494
  }
381
- return { data: B, doctype: p, count: N };
495
+ return { data: y, doctype: m, hasMore: f, count: k };
382
496
  })
383
497
  )
384
498
  );
@@ -387,55 +501,125 @@ const kt = ft`
387
501
  },
388
502
  Mutation: {
389
503
  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)
504
+ stonecropAction(l, { $doctype: d, $action: b, $args: v }) {
505
+ return Ee(
506
+ i,
507
+ ee({ doctype: d, action: b, actionArgs: v }),
508
+ async (R, h) => {
509
+ const w = I(String(h.doctype));
510
+ if (!w)
404
511
  return {
405
512
  success: !1,
406
513
  data: null,
407
- error: `Unknown action: ${u.action} on ${u.doctype}`
514
+ error: `Unknown doctype: ${h.doctype}`
408
515
  };
409
- const r = Q(S);
410
- if (!r)
516
+ const M = w.workflow?.actions?.[h.action];
517
+ if (!M)
411
518
  return {
412
519
  success: !1,
413
520
  data: null,
414
- error: `No primary key for doctype: ${u.doctype}`
521
+ error: `Unknown action: ${h.action} on ${h.doctype}`
415
522
  };
416
- const p = A(r.fieldname), a = C(S.name, t.tables), b = (Array.isArray(u.actionArgs) ? u.actionArgs : [])[0]?.id;
417
- 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
- });
523
+ const g = W(w.name, t.tables), c = () => {
524
+ const s = te(w);
525
+ if (!s) throw ne(String(h.doctype));
526
+ return A(s.fieldname);
527
+ }, m = Array.isArray(h.actionArgs) ? h.actionArgs : [], p = m[0]?.id, B = m[0]?.data ?? {}, H = t.actionHandlers?.[w.name]?.[String(h.action)], O = new Map(
528
+ X(w.fields).filter((s) => A(s.fieldname) !== Q).map((s) => [s.fieldname, s])
529
+ ), D = X(w.fields).some(
530
+ (s) => A(s.fieldname) === Q
531
+ ), L = [], q = (s) => {
532
+ const $ = [], a = [];
533
+ for (const [f, y] of Object.entries(s)) {
534
+ if (!O.has(f)) {
535
+ L.push(f);
536
+ continue;
537
+ }
538
+ if (y !== null && typeof y == "object") {
539
+ L.push(f);
540
+ continue;
432
541
  }
542
+ $.push(A(f)), a.push(y);
543
+ }
544
+ return { cols: $, values: a };
545
+ };
546
+ try {
547
+ return await R.withTransaction(async (s) => {
548
+ const $ = await De(
549
+ M,
550
+ {
551
+ readState: async () => {
552
+ if (p == null) return null;
553
+ const a = D ? `"${Q}"` : `"${c()}"`, { rows: f } = await e(s, {
554
+ text: `SELECT ${a} FROM ${g} WHERE "${c()}"::text = $1 FOR UPDATE`,
555
+ values: [String(p)]
556
+ });
557
+ if (f.length === 0) return null;
558
+ if (D)
559
+ return f[0][Q] ?? void 0;
560
+ },
561
+ writeState: async (a) => {
562
+ await e(s, {
563
+ text: `UPDATE ${g} SET "${Q}" = $1 WHERE "${c()}"::text = $2`,
564
+ values: [a, String(p)]
565
+ });
566
+ },
567
+ // The upsert, and the only write path for record data. `exists`
568
+ // comes from the guard's own read, so no second lookup decides it.
569
+ //
570
+ // Returns the same projection the read path selects, never
571
+ // `RETURNING *`: raw columns come back snake_case, and the client
572
+ // resolves identity by the *declared fieldname*. A doctype keyed
573
+ // `itemId` would receive `item_id`, find no identity, and file a
574
+ // created record nowhere — which is that exact bug, already once
575
+ // shipped and patched downstream.
576
+ writeData: async (a, f) => {
577
+ const { cols: y, values: k } = q(a), u = Y(w);
578
+ if (!f) {
579
+ if (p != null)
580
+ throw new Error(
581
+ `Action "${M.label ?? h.action}" targets ${w.name} "${String(p)}", which no longer exists. Nothing was created — a record dispatched with an identity is an update, and creating one is what dispatching no identity means.`
582
+ );
583
+ const S = y.length ? `INSERT INTO ${g} (${y.map((x) => `"${x}"`).join(", ")}) VALUES (${y.map((x, T) => `$${T + 1}`).join(", ")}) RETURNING ${u}` : `INSERT INTO ${g} DEFAULT VALUES RETURNING ${u}`, { rows: F } = await e(s, { text: S, values: k });
584
+ return F[0] ?? {};
585
+ }
586
+ if (y.length === 0) {
587
+ const { rows: S } = await e(s, {
588
+ text: `SELECT ${u} FROM ${g} WHERE "${c()}"::text = $1`,
589
+ values: [String(p)]
590
+ });
591
+ return S[0] ?? {};
592
+ }
593
+ const E = y.map((S, F) => `"${S}" = $${F + 1}`).join(", "), { rows: N } = await e(s, {
594
+ text: `UPDATE ${g} SET ${E} WHERE "${c()}"::text = $${y.length + 1} RETURNING ${u}`,
595
+ values: [...k, String(p)]
596
+ });
597
+ return N[0] ?? {};
598
+ },
599
+ runEffect: H ? (a) => H({
600
+ pgClient: s,
601
+ doctype: String(h.doctype),
602
+ action: String(h.action),
603
+ meta: w,
604
+ recordId: p,
605
+ data: B,
606
+ args: m,
607
+ currentState: a
608
+ }) : void 0
609
+ },
610
+ // The patch a self-transition persists. This adapter never passed it, which
611
+ // was moot while it had no `writeData` — nothing consumed it. Wiring the write
612
+ // without this argument saves an empty record and reports success.
613
+ B
614
+ );
615
+ if (!$.success) throw new le($);
616
+ return L.length ? { ...$, droppedFields: L } : $;
433
617
  });
434
- } catch (c) {
435
- return {
618
+ } catch (s) {
619
+ return s instanceof le ? s.outcome : {
436
620
  success: !1,
437
621
  data: null,
438
- error: c instanceof Error ? c.message : String(c)
622
+ error: s instanceof Error ? s.message : String(s)
439
623
  };
440
624
  }
441
625
  }
@@ -447,48 +631,89 @@ const kt = ft`
447
631
  };
448
632
  });
449
633
  };
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;
455
- }
456
- function Et(t, e) {
634
+ function Ie(t, e) {
457
635
  const o = [];
458
- for (const n of K(t)) {
459
- 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}"`);
636
+ for (const n of X(t)) {
637
+ const r = e.get(n.fieldname);
638
+ if (r && oe(r, n.component) !== "inline") continue;
639
+ const i = A(n.fieldname);
640
+ o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
464
641
  }
465
642
  return o;
466
643
  }
467
- function U(t) {
644
+ function Y(t) {
468
645
  const e = /* @__PURE__ */ new Map();
469
646
  if (t.links)
470
647
  for (const [o, n] of Object.entries(t.links))
471
648
  e.set(n.fieldname ?? o, n);
472
- return Et(t.fields, e).join(", ");
649
+ return Ie(t.fields, e).join(", ");
650
+ }
651
+ function te(t) {
652
+ const e = ke(t.fields);
653
+ return t.fields.find((o) => o.kind === "field" && o.fieldname === e);
654
+ }
655
+ function Be(t) {
656
+ const e = Object.entries(t);
657
+ if (e.length === 0) return;
658
+ if (he().length === 0) {
659
+ console.warn(
660
+ "[@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."
661
+ );
662
+ return;
663
+ }
664
+ const o = [];
665
+ for (const [n, r] of e) {
666
+ const i = I(n);
667
+ if (!i) {
668
+ o.push(`"${n}": no doctype by that name is registered`);
669
+ continue;
670
+ }
671
+ if (i.name !== n) {
672
+ o.push(
673
+ `"${n}": matches the doctype named "${i.name}" by slug, but handlers are looked up by name — key it "${i.name}"`
674
+ );
675
+ continue;
676
+ }
677
+ const l = i.workflow?.actions ?? {};
678
+ for (const d of Object.keys(r))
679
+ d in l || o.push(`"${n}.${d}": the doctype declares no action by that key`);
680
+ }
681
+ if (o.length > 0)
682
+ throw new Error(
683
+ `StonecropPlugin: ${o.length} registered action handler${o.length === 1 ? "" : "s"} cannot be reached and would never run:
684
+ ${o.join(`
685
+ `)}`
686
+ );
687
+ }
688
+ function je() {
689
+ const t = Le();
690
+ if (t.length !== 0)
691
+ throw new Error(
692
+ `StonecropPlugin: ${t.length} doctype reference${t.length === 1 ? "" : "s"} cannot be resolved and would silently drop the relation:
693
+ ` + t.map((e) => `${e.path.join(".")}: ${e.message}`).join(`
694
+ `)
695
+ );
473
696
  }
474
- function Q(t) {
475
- return it(t.fields);
697
+ function ne(t) {
698
+ return new Error(
699
+ `Doctype "${t}" 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.`
700
+ );
476
701
  }
477
- function C(t, e) {
478
- const o = e?.[t] ?? at(t), n = o.indexOf(".");
702
+ function W(t, e) {
703
+ const o = e?.[t] ?? $e(t), n = o.indexOf(".");
479
704
  return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
480
705
  }
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();
706
+ const et = (t = {}) => {
707
+ const { logPlans: e = !0, logTiming: o = !1 } = t, n = (r, i) => ({
708
+ plan: (l) => {
709
+ e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
710
+ const d = o ? Date.now() : 0, b = l();
486
711
  return o && console.log(
487
- `[@stonecrop/graphql-middleware] Plan built for ${s}.${l} in ${Date.now() - y}ms`
488
- ), M;
712
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - d}ms`
713
+ ), b;
489
714
  }
490
715
  });
491
- return gt({
716
+ return Me({
492
717
  Query: {
493
718
  stonecropRecord: n("Query", "stonecropRecord"),
494
719
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -499,7 +724,7 @@ const Wt = (t = {}) => {
499
724
  stonecropAction: n("Mutation", "stonecropAction")
500
725
  }
501
726
  });
502
- }, Mt = {
727
+ }, Ce = {
503
728
  name: "StonecropFieldCasingPlugin",
504
729
  version: "0.0.0",
505
730
  inflection: {
@@ -509,28 +734,27 @@ const Wt = (t = {}) => {
509
734
  }
510
735
  }
511
736
  }
512
- }, Rt = (t) => ({
513
- extends: [yt],
514
- plugins: t?.fieldCasing === "pascal" ? [Mt] : []
515
- }), Jt = Rt();
737
+ }, Pe = (t) => ({
738
+ extends: [Oe],
739
+ plugins: t?.fieldCasing === "pascal" ? [Ce] : []
740
+ }), tt = Pe();
516
741
  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
742
+ re as DoctypeValidationError,
743
+ tt as StonecropPreset,
744
+ De as applyGuardedTransition,
745
+ Xe as clearFetchHandlers,
746
+ ze as clearRegistry,
747
+ et as createDebugPlugin,
748
+ Ze as createStonecropPlugin,
749
+ Pe as createStonecropPreset,
750
+ he as getAllMeta,
751
+ Ne as getFetchHandler,
752
+ I as getMeta,
753
+ Ve as hasMeta,
754
+ xe as loadDoctypes,
755
+ Qe as loadDoctypesFromObject,
756
+ rt as makePgService,
757
+ Ye as registerFetchHandler,
758
+ Fe as typeDefs
535
759
  };
536
760
  //# sourceMappingURL=index.js.map