@stonecrop/graphql-middleware 0.17.0 → 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,31 +1,40 @@
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) {
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 {
20
+ constructor(e, o) {
12
21
  const n = o.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
13
22
  `);
14
- super(`Invalid doctype definition in ${t}:
15
- ${n}`), this.file = t, this.errors = o, this.name = "DoctypeValidationError";
23
+ super(`Invalid doctype definition in ${e}:
24
+ ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
16
25
  }
17
26
  file;
18
27
  errors;
19
28
  }
20
- function Se(e, t = {}) {
21
- const o = re(e);
29
+ function xe(t, e = {}) {
30
+ const o = ge(t);
22
31
  for (const n of o) {
23
- const r = ae(e, n);
24
- se(r).isDirectory() ? Se(r, t) : n.endsWith(".json") && $e(r, t);
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 $e(e, t) {
28
- const o = ie(e, "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);
@@ -34,112 +43,134 @@ function $e(e, t) {
34
43
  path: [],
35
44
  message: `Invalid JSON: ${l instanceof Error ? l.message : String(l)}`
36
45
  };
37
- if (t.continueOnError) {
38
- t.onError?.(e, [d]);
46
+ if (e.continueOnError) {
47
+ e.onError?.(t, [d]);
39
48
  return;
40
49
  }
41
- throw new G(e, [d]);
50
+ throw new re(t, [d]);
42
51
  }
43
- const r = te(n);
52
+ const r = ue(n);
44
53
  if (!r.success) {
45
- if (t.continueOnError) {
46
- t.onError?.(e, r.errors);
54
+ if (e.continueOnError) {
55
+ e.onError?.(t, r.errors);
47
56
  return;
48
57
  }
49
- throw new G(e, r.errors);
58
+ throw new re(t, r.errors);
50
59
  }
51
- const i = ne(n);
52
- C.set(i.name, i);
60
+ const i = fe(n);
61
+ P.set(i.name, i);
53
62
  }
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);
63
+ function Qe(t, e = {}) {
64
+ for (const [o, n] of Object.entries(t)) {
65
+ const r = { ...typeof n == "object" && n !== null ? n : {}, name: o }, i = ue(r);
57
66
  if (!i.success) {
58
- if (t.continueOnError) {
59
- t.onError?.(o, i.errors);
67
+ if (e.continueOnError) {
68
+ e.onError?.(o, i.errors);
60
69
  continue;
61
70
  }
62
- throw new G(o, i.errors);
71
+ throw new re(o, i.errors);
63
72
  }
64
- const l = ne(r);
65
- C.set(l.name, l);
73
+ const l = fe(r);
74
+ P.set(l.name, l);
66
75
  }
67
76
  }
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;
77
+ function I(t) {
78
+ const e = P.get(t);
79
+ if (e) return e;
80
+ for (const o of P.values())
81
+ if (o.slug === t) return o;
73
82
  }
74
- function oe() {
75
- return Array.from(C.values());
83
+ function he() {
84
+ return Array.from(P.values());
76
85
  }
77
- function Pe(e) {
78
- return C.has(e);
86
+ function Ve(t) {
87
+ return P.has(t);
79
88
  }
80
- function We() {
81
- C.clear();
89
+ function ze() {
90
+ P.clear();
82
91
  }
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}`
92
+ function Le() {
93
+ const t = [];
94
+ for (const e of P.values()) {
95
+ e.inherits && I(e.inherits) === void 0 && t.push({
96
+ path: [e.name, "inherits"],
97
+ message: `References unknown doctype: ${e.inherits}`
89
98
  });
90
- for (const o of t.fields) {
91
- if (o.kind !== "field") continue;
92
- const n = o.doctype;
93
- n !== void 0 && M(n) === void 0 && e.push({
94
- path: [t.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 (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
- 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
- return e;
136
+ return t;
106
137
  }
107
- const K = /* @__PURE__ */ new Map();
108
- function qe(e, t) {
109
- K.set(e, t);
138
+ const ie = /* @__PURE__ */ new Map();
139
+ function Ye(t, e) {
140
+ ie.set(t, e);
110
141
  }
111
- function Ee(e) {
112
- return K.get(e);
142
+ function Ne(t) {
143
+ return ie.get(t);
113
144
  }
114
- function He() {
115
- K.clear();
145
+ function Xe() {
146
+ ie.clear();
116
147
  }
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)
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)
120
151
  return {
121
152
  success: !1,
122
153
  data: null,
123
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.`
124
155
  };
125
- if (r && !t.writeData && !t.runEffect)
156
+ if (r && !e.writeData && !e.runEffect)
126
157
  return {
127
158
  success: !1,
128
159
  data: null,
129
160
  error: `Action "${n}" persists record data in place, which this backend does not support.`
130
161
  };
131
- const l = (e.allowedStates?.length ?? 0) > 0;
162
+ const l = (t.allowedStates?.length ?? 0) > 0;
132
163
  let d;
133
164
  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 ? {
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 ? {
139
170
  success: !1,
140
171
  data: null,
141
172
  error: `Action "${n}" targets a record that does not exist, and the backend did not create it.`
142
- } : { success: !0, data: a, error: null };
173
+ } : { success: !0, data: R, error: null };
143
174
  }
144
175
  return {
145
176
  success: !1,
@@ -147,32 +178,32 @@ async function be(e, t, o) {
147
178
  error: `Action "${n}" targets a record that does not exist — nothing was executed.`
148
179
  };
149
180
  }
150
- d = h ?? "";
181
+ d = v ?? "";
151
182
  }
152
- if (!ce(e, d ?? ""))
183
+ if (!Se(t, d ?? ""))
153
184
  return {
154
185
  success: !1,
155
186
  data: null,
156
187
  error: `Action not allowed from state: ${d || "(unknown)"}`
157
188
  };
158
- let S;
159
- if (t.runEffect)
189
+ let b;
190
+ if (e.runEffect)
160
191
  try {
161
- S = await t.runEffect(d);
162
- } catch (h) {
192
+ b = await e.runEffect(d);
193
+ } catch (v) {
163
194
  return {
164
195
  success: !1,
165
196
  data: null,
166
- error: `Action "${n}" failed: ${h instanceof Error ? h.message : String(h)}`
197
+ error: `Action "${n}" failed: ${v instanceof Error ? v.message : String(v)}`
167
198
  };
168
199
  }
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), {
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), {
170
201
  success: !0,
171
- data: S ?? { state: e.nextState },
202
+ data: b ?? { state: t.nextState },
172
203
  error: null
173
204
  });
174
205
  }
175
- const ve = he`
206
+ const Fe = Re`
176
207
  type StonecropFieldMeta {
177
208
  kind: String!
178
209
  fieldname: String!
@@ -225,6 +256,13 @@ const ve = he`
225
256
  data: JSON
226
257
  doctype: String!
227
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!]
228
266
  }
229
267
 
230
268
  type StonecropRecordsResult {
@@ -246,6 +284,14 @@ const ve = he`
246
284
  success: Boolean!
247
285
  data: JSON
248
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!]
249
295
  }
250
296
 
251
297
  extend type Query {
@@ -267,176 +313,186 @@ const ve = he`
267
313
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
268
314
  }
269
315
  `;
270
- class ee extends Error {
271
- constructor(t) {
272
- super(t.error ?? "Action failed"), this.outcome = t, this.name = "ActionRolledBack";
316
+ class le extends Error {
317
+ constructor(e) {
318
+ super(e.error ?? "Action failed"), this.outcome = e, this.name = "ActionRolledBack";
273
319
  }
274
320
  outcome;
275
321
  }
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)
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)
281
327
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
282
- return e.actionHandlers && Me(e.actionHandlers), Ae(), {
283
- typeDefs: ve,
328
+ return t.actionHandlers && Be(t.actionHandlers), je(), {
329
+ typeDefs: Fe,
284
330
  objects: {
285
331
  Query: {
286
332
  plans: {
287
- stonecropMeta(i, { $doctype: l }) {
288
- return pe(l, (d) => M(String(d)) ?? null);
333
+ stonecropMeta(l, { $doctype: d }) {
334
+ return ve(d, (b) => I(String(b)) ?? null);
289
335
  },
290
336
  stonecropAllMeta() {
291
- return ge(oe());
337
+ return be(he());
292
338
  },
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);
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);
302
348
  }
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 };
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 };
308
354
  continue;
309
355
  }
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)
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}` });
363
+ }
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)
317
372
  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.`
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.`
319
374
  );
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 };
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 };
324
379
  continue;
325
380
  }
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));
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));
334
389
  continue;
335
390
  }
336
- if (W !== "sync" && !O?.has(u)) continue;
337
- const L = M(m.target);
338
- if (!L) continue;
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
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
349
404
  });
350
- E[u] = J;
405
+ G != null && K.length > G ? (u.push(j), k[j] = K.slice(0, G)) : k[j] = K;
351
406
  } else {
352
- if (!m.fieldname) continue;
353
- const P = E[m.fieldname];
354
- if (P == null) {
355
- E[u] = null;
407
+ const _ = k[`${de}${j}`];
408
+ if (_ == null) {
409
+ k[j] = null;
356
410
  continue;
357
411
  }
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]
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: [_]
363
417
  });
364
- E[u] = J[0] ?? null;
418
+ k[j] = K[0] ?? null;
365
419
  }
366
420
  }
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
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
372
428
  };
373
429
  }
374
430
  }
375
- return R;
431
+ return M;
376
432
  }
377
433
  );
378
434
  },
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: $
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
389
445
  }),
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}`);
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}`);
401
457
  }
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}`;
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}`;
417
473
  }
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}`,
425
- values: c
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
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
436
492
  });
437
- O = parseInt(v[0]?.row_count ?? "0", 10);
493
+ k = parseInt(S[0]?.row_count ?? "0", 10);
438
494
  }
439
- return { data: H, doctype: f, hasMore: j, count: O };
495
+ return { data: y, doctype: m, hasMore: f, count: k };
440
496
  })
441
497
  )
442
498
  );
@@ -445,66 +501,125 @@ const Je = (e = {}) => {
445
501
  },
446
502
  Mutation: {
447
503
  plans: {
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 (!$)
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)
455
511
  return {
456
512
  success: !1,
457
513
  data: null,
458
- error: `Unknown doctype: ${a.doctype}`
514
+ error: `Unknown doctype: ${h.doctype}`
459
515
  };
460
- const R = $.workflow?.actions?.[a.action];
461
- if (!R)
516
+ const M = w.workflow?.actions?.[h.action];
517
+ if (!M)
462
518
  return {
463
519
  success: !1,
464
520
  data: null,
465
- error: `Unknown action: ${a.action} on ${a.doctype}`
521
+ error: `Unknown action: ${h.action} on ${h.doctype}`
466
522
  };
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)];
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;
541
+ }
542
+ $.push(A(f)), a.push(y);
543
+ }
544
+ return { cols: $, values: a };
545
+ };
472
546
  try {
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
- });
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
488
609
  },
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;
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 } : $;
502
617
  });
503
- } catch (c) {
504
- return c instanceof ee ? c.outcome : {
618
+ } catch (s) {
619
+ return s instanceof le ? s.outcome : {
505
620
  success: !1,
506
621
  data: null,
507
- error: c instanceof Error ? c.message : String(c)
622
+ error: s instanceof Error ? s.message : String(s)
508
623
  };
509
624
  }
510
625
  }
@@ -516,46 +631,39 @@ const Je = (e = {}) => {
516
631
  };
517
632
  });
518
633
  };
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;
524
- }
525
- function Re(e, t) {
634
+ function Ie(t, e) {
526
635
  const o = [];
527
- for (const n of z(e)) {
528
- if (n.kind !== "field" || n.computed) continue;
529
- const r = t.get(n.fieldname);
530
- if (r && ue(r, n.component) !== "inline") continue;
531
- const i = D(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);
532
640
  o.push(i !== n.fieldname ? `"${i}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
533
641
  }
534
642
  return o;
535
643
  }
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(", ");
644
+ function Y(t) {
645
+ const e = /* @__PURE__ */ new Map();
646
+ if (t.links)
647
+ for (const [o, n] of Object.entries(t.links))
648
+ e.set(n.fieldname ?? o, n);
649
+ return Ie(t.fields, e).join(", ");
542
650
  }
543
- function Q(e) {
544
- const t = de(e.fields);
545
- return e.fields.find((o) => o.kind === "field" && o.fieldname === t);
651
+ function te(t) {
652
+ const e = ke(t.fields);
653
+ return t.fields.find((o) => o.kind === "field" && o.fieldname === e);
546
654
  }
547
- function Me(e) {
548
- const t = Object.entries(e);
549
- if (t.length === 0) return;
550
- if (oe().length === 0) {
655
+ function Be(t) {
656
+ const e = Object.entries(t);
657
+ if (e.length === 0) return;
658
+ if (he().length === 0) {
551
659
  console.warn(
552
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."
553
661
  );
554
662
  return;
555
663
  }
556
664
  const o = [];
557
- for (const [n, r] of t) {
558
- const i = M(n);
665
+ for (const [n, r] of e) {
666
+ const i = I(n);
559
667
  if (!i) {
560
668
  o.push(`"${n}": no doctype by that name is registered`);
561
669
  continue;
@@ -577,35 +685,35 @@ function Me(e) {
577
685
  `)}`
578
686
  );
579
687
  }
580
- function Ae() {
581
- const e = ke();
582
- if (e.length !== 0)
688
+ function je() {
689
+ const t = Le();
690
+ if (t.length !== 0)
583
691
  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(`
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(`
586
694
  `)
587
695
  );
588
696
  }
589
- function V(e) {
697
+ function ne(t) {
590
698
  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.`
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.`
592
700
  );
593
701
  }
594
- function B(e, t) {
595
- const o = t?.[e] ?? le(e), n = o.indexOf(".");
702
+ function W(t, e) {
703
+ const o = e?.[t] ?? $e(t), n = o.indexOf(".");
596
704
  return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
597
705
  }
598
- const _e = (e = {}) => {
599
- const { logPlans: t = !0, logTiming: o = !1 } = e, n = (r, i) => ({
706
+ const et = (t = {}) => {
707
+ const { logPlans: e = !0, logTiming: o = !1 } = t, n = (r, i) => ({
600
708
  plan: (l) => {
601
- t && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
602
- const d = o ? Date.now() : 0, S = l();
709
+ e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
710
+ const d = o ? Date.now() : 0, b = l();
603
711
  return o && console.log(
604
712
  `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - d}ms`
605
- ), S;
713
+ ), b;
606
714
  }
607
715
  });
608
- return me({
716
+ return Me({
609
717
  Query: {
610
718
  stonecropRecord: n("Query", "stonecropRecord"),
611
719
  stonecropRecords: n("Query", "stonecropRecords"),
@@ -616,37 +724,37 @@ const _e = (e = {}) => {
616
724
  stonecropAction: n("Mutation", "stonecropAction")
617
725
  }
618
726
  });
619
- }, Oe = {
727
+ }, Ce = {
620
728
  name: "StonecropFieldCasingPlugin",
621
729
  version: "0.0.0",
622
730
  inflection: {
623
731
  replace: {
624
- attribute(e, t, o) {
732
+ attribute(t, e, o) {
625
733
  return this.upperCamelCase(this._attributeName(o));
626
734
  }
627
735
  }
628
736
  }
629
- }, xe = (e) => ({
630
- extends: [we],
631
- plugins: e?.fieldCasing === "pascal" ? [Oe] : []
632
- }), Ue = xe();
737
+ }, Pe = (t) => ({
738
+ extends: [Oe],
739
+ plugins: t?.fieldCasing === "pascal" ? [Ce] : []
740
+ }), tt = Pe();
633
741
  export {
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
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
651
759
  };
652
760
  //# sourceMappingURL=index.js.map