@stonecrop/graphql-middleware 0.13.14 → 0.15.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.
Files changed (40) hide show
  1. package/README.md +19 -18
  2. package/dist/graphql-middleware.d.ts +44 -74
  3. package/dist/index.js +314 -354
  4. package/dist/index.js.map +1 -1
  5. package/dist/src/dispatch/transition.d.ts +20 -8
  6. package/dist/src/dispatch/transition.d.ts.map +1 -1
  7. package/dist/src/dispatch/transition.js +33 -9
  8. package/dist/src/index.d.ts +2 -2
  9. package/dist/src/index.d.ts.map +1 -1
  10. package/dist/src/index.js +2 -2
  11. package/dist/src/plugin/postgraphile.d.ts +3 -3
  12. package/dist/src/plugin/postgraphile.d.ts.map +1 -1
  13. package/dist/src/plugin/postgraphile.js +48 -23
  14. package/dist/src/registry/doctypes.d.ts.map +1 -1
  15. package/dist/src/registry/doctypes.js +17 -5
  16. package/dist/src/typeDefs.d.ts.map +1 -1
  17. package/dist/src/typeDefs.js +15 -10
  18. package/package.json +11 -6
  19. package/dist/plugin/postgraphile.js +0 -583
  20. package/dist/preset.js +0 -45
  21. package/dist/registry/actions.js +0 -163
  22. package/dist/registry/doctypes.js +0 -161
  23. package/dist/src/registry/actions.d.ts +0 -36
  24. package/dist/src/registry/actions.d.ts.map +0 -1
  25. package/dist/src/registry/actions.js +0 -169
  26. package/dist/src/types/context.d.ts +0 -20
  27. package/dist/src/types/context.d.ts.map +0 -1
  28. package/dist/src/types/index.d.ts +0 -46
  29. package/dist/src/types/index.d.ts.map +0 -1
  30. package/dist/src/types/index.js +0 -3
  31. package/dist/src/types/preset.d.ts +0 -18
  32. package/dist/src/types/preset.d.ts.map +0 -1
  33. package/dist/src/types/query.d.ts +0 -132
  34. package/dist/src/types/query.d.ts.map +0 -1
  35. package/dist/src/types/query.js +0 -3
  36. package/dist/typeDefs.js +0 -79
  37. package/dist/types/context.js +0 -0
  38. package/dist/types/index.js +0 -3
  39. package/dist/types/preset.js +0 -0
  40. package/dist/types/query.js +0 -3
package/dist/index.js CHANGED
@@ -1,227 +1,175 @@
1
- import { readdirSync as ne, statSync as oe, readFileSync as re } from "node:fs";
2
- import { join as ie } from "node:path";
3
- import { validateDoctype as ee, parseDoctype as te, camelToSnake as x, pascalToSnake as se } from "@stonecrop/schema";
4
- import { sideEffectWithPgClient as ce, loadOneWithPgClient as X } from "@dataplan/pg";
5
- import { object as Q, constant as ae, lambda as le } from "postgraphile/grafast";
6
- import { gql as de, extendSchema as fe, wrapPlans as ue } from "postgraphile/utils";
7
- import { PostGraphileAmberPreset as pe } from "postgraphile/presets/amber";
8
- import { makePgService as Ke } from "postgraphile/adaptors/pg";
9
- const $ = /* @__PURE__ */ new Map();
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, pascalToSnake as it, resolveLinkRenderMode as at } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as ct, loadOneWithPgClient as X } from "@dataplan/pg";
5
+ import { object as q, constant as lt, lambda as ut } from "postgraphile/grafast";
6
+ import { gql as dt, extendSchema as ft, wrapPlans as pt } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as gt } from "postgraphile/presets/amber";
8
+ import { makePgService as _t } from "postgraphile/adaptors/pg";
9
+ const w = /* @__PURE__ */ new Map();
10
10
  class V extends Error {
11
- constructor(e, n) {
12
- const o = n.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
11
+ constructor(e, o) {
12
+ const n = o.map((s) => ` ${s.path.join(".")}: ${s.message}`).join(`
13
13
  `);
14
14
  super(`Invalid doctype definition in ${e}:
15
- ${o}`), this.file = e, this.errors = n, this.name = "DoctypeValidationError";
15
+ ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
16
16
  }
17
17
  file;
18
18
  errors;
19
19
  }
20
- function ye(t, e = {}) {
21
- const n = ne(t);
22
- for (const o of n) {
23
- const r = ie(t, o);
24
- oe(r).isDirectory() ? ye(r, e) : o.endsWith(".json") && ge(r, e);
20
+ function yt(t, e = {}) {
21
+ const o = et(t);
22
+ for (const n of o) {
23
+ const s = rt(t, n);
24
+ nt(s).isDirectory() ? yt(s, e) : n.endsWith(".json") && St(s, e);
25
25
  }
26
26
  }
27
- function ge(t, e) {
28
- const n = re(t, "utf-8");
29
- let o;
27
+ function St(t, e) {
28
+ const o = ot(t, "utf-8");
29
+ let n;
30
30
  try {
31
- o = JSON.parse(n);
32
- } catch (c) {
33
- const a = {
31
+ n = JSON.parse(o);
32
+ } catch (f) {
33
+ const y = {
34
34
  path: [],
35
- message: `Invalid JSON: ${c instanceof Error ? c.message : String(c)}`
35
+ message: `Invalid JSON: ${f instanceof Error ? f.message : String(f)}`
36
36
  };
37
37
  if (e.continueOnError) {
38
- e.onError?.(t, [a]);
38
+ e.onError?.(t, [y]);
39
39
  return;
40
40
  }
41
- throw new V(t, [a]);
41
+ throw new V(t, [y]);
42
42
  }
43
- const r = ee(o);
44
- if (!r.success) {
43
+ const s = Z(n);
44
+ if (!s.success) {
45
45
  if (e.continueOnError) {
46
- e.onError?.(t, r.errors);
46
+ e.onError?.(t, s.errors);
47
47
  return;
48
48
  }
49
- throw new V(t, r.errors);
49
+ throw new V(t, s.errors);
50
50
  }
51
- const i = te(o);
52
- $.set(i.name, i);
51
+ const l = tt(n);
52
+ w.set(l.name, l);
53
53
  }
54
- function Le(t, e = {}) {
55
- for (const [n, o] of Object.entries(t)) {
56
- const r = { ...typeof o == "object" && o !== null ? o : {}, name: n }, i = ee(r);
57
- if (!i.success) {
54
+ function Ft(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
58
  if (e.continueOnError) {
59
- e.onError?.(n, i.errors);
59
+ e.onError?.(o, l.errors);
60
60
  continue;
61
61
  }
62
- throw new V(n, i.errors);
62
+ throw new V(o, l.errors);
63
63
  }
64
- const c = te(r);
65
- $.set(c.name, c);
64
+ const f = tt(s);
65
+ w.set(f.name, f);
66
66
  }
67
67
  }
68
- function I(t) {
69
- const e = $.get(t);
68
+ function T(t) {
69
+ const e = w.get(t);
70
70
  if (e) return e;
71
- for (const n of $.values())
72
- if (n.slug === t) return n;
71
+ for (const o of w.values())
72
+ if (o.slug === t) return o;
73
73
  }
74
- function me() {
75
- return Array.from($.values());
74
+ function mt() {
75
+ return Array.from(w.values());
76
76
  }
77
- function Pe(t) {
78
- return $.has(t);
77
+ function Nt(t) {
78
+ return w.has(t);
79
79
  }
80
- function Te() {
81
- $.clear();
80
+ function It() {
81
+ w.clear();
82
82
  }
83
- function He() {
83
+ function Dt() {
84
84
  const t = [];
85
- for (const e of $.values()) {
86
- e.inherits && !$.has(e.inherits) && t.push({
85
+ for (const e of w.values()) {
86
+ e.inherits && !w.has(e.inherits) && t.push({
87
87
  path: [e.name, "inherits"],
88
88
  message: `References unknown doctype: ${e.inherits}`
89
89
  });
90
- for (const n of e.fields)
91
- n.kind === "field" && n.fieldtype === "Link" && typeof n.options == "string" && ($.has(n.options) || t.push({
92
- path: [e.name, "fields", n.fieldname, "options"],
93
- message: `Link references unknown doctype: ${n.options}`
94
- }));
95
- }
96
- return t;
97
- }
98
- const T = /* @__PURE__ */ new Map();
99
- function he(t, e) {
100
- T.set(t, e);
101
- }
102
- function Se(t) {
103
- return T.get(t);
104
- }
105
- function Je(t) {
106
- return T.has(t);
107
- }
108
- function We() {
109
- T.clear();
110
- }
111
- const $e = async (t, e) => {
112
- const [n] = t, { doctype: o } = e, r = [];
113
- for (const i of o.fields)
114
- i.kind === "field" && i.required && (n[i.fieldname] === void 0 || n[i.fieldname] === null) && r.push(i.label ?? i.fieldname);
115
- if (r.length > 0)
116
- throw new Error(`Missing required fields: ${r.join(", ")}`);
117
- return { valid: !0 };
118
- }, we = async (t, e) => {
119
- const [n] = t, { doctype: o } = e, r = [];
120
- for (const i of o.fields) {
121
- if (i.kind !== "field") continue;
122
- const c = n[i.fieldname];
123
- if (c == null) continue;
124
- const a = ke(i, c);
125
- a && r.push(a);
126
- }
127
- if (o.links)
128
- for (const [i, c] of Object.entries(o.links)) {
129
- const a = n[i];
130
- if (a == null) continue;
131
- c.cardinality === "noneOrMany" || c.cardinality === "atLeastOne" ? Array.isArray(a) || r.push(`${i}: expected array, got ${typeof a}`) : (typeof a != "object" || Array.isArray(a)) && r.push(`${i}: expected object, got ${typeof a}`);
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}`
96
+ });
132
97
  }
133
- if (r.length > 0)
134
- throw new Error(`Field type validation failed:
135
- ${r.join(`
136
- `)}`);
137
- return { valid: !0 };
138
- };
139
- function ke(t, e) {
140
- const { fieldname: n, fieldtype: o } = t;
141
- switch (o) {
142
- case "Int":
143
- if (typeof e != "number" || !Number.isInteger(e))
144
- return `${n}: expected integer, got ${typeof e}`;
145
- break;
146
- case "Float":
147
- case "Decimal":
148
- case "Currency":
149
- case "Quantity":
150
- if (typeof e != "number" && typeof e != "string")
151
- return `${n}: expected number, got ${typeof e}`;
152
- break;
153
- case "Check":
154
- if (typeof e != "boolean")
155
- return `${n}: expected boolean, got ${typeof e}`;
156
- break;
157
- case "Data":
158
- case "Text":
159
- case "Code":
160
- case "Link":
161
- if (typeof e != "string")
162
- return `${n}: expected string, got ${typeof e}`;
163
- break;
164
- case "Date":
165
- case "Time":
166
- case "Datetime":
167
- if (typeof e != "string" && !(e instanceof Date))
168
- return `${n}: expected date string or Date, got ${typeof e}`;
169
- break;
170
- case "JSON":
171
- if (typeof e != "object")
172
- return `${n}: expected object, got ${typeof e}`;
173
- break;
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}`
103
+ });
174
104
  }
175
- return null;
105
+ return t;
176
106
  }
177
- const Ee = async () => ({ ok: !0 }), be = {
178
- validateRequiredFields: $e,
179
- validateFieldTypes: we,
180
- noop: Ee
181
- };
182
- function qe() {
183
- for (const [t, e] of Object.entries(be))
184
- he(t, e);
107
+ const G = /* @__PURE__ */ new Map();
108
+ function Lt(t, e) {
109
+ G.set(t, e);
185
110
  }
186
- const Y = /* @__PURE__ */ new Map();
187
- function _e(t, e) {
188
- Y.set(t, e);
111
+ function wt(t) {
112
+ return G.get(t);
189
113
  }
190
- function Me(t) {
191
- return Y.get(t);
114
+ function Tt() {
115
+ G.clear();
192
116
  }
193
- function Qe() {
194
- Y.clear();
117
+ async function ht(t, e, o) {
118
+ if (!t.selfTransition && t.nextState == null)
119
+ return {
120
+ success: !1,
121
+ data: null,
122
+ error: `Action "${t.label ?? "unknown"}" has no workflow transition and no server-side effect is wired — nothing was executed.`
123
+ };
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), {
130
+ success: !0,
131
+ data: { state: t.nextState },
132
+ error: null
133
+ }) : {
134
+ success: !1,
135
+ data: null,
136
+ error: `Action not allowed from state: ${n || "(unknown)"}`
137
+ };
195
138
  }
196
- const Oe = de`
139
+ const $t = dt`
197
140
  type StonecropFieldMeta {
198
141
  kind: String!
199
142
  fieldname: String!
200
- fieldtype: String!
201
143
  component: String
144
+ primaryKey: Boolean
145
+ computed: Boolean
146
+ language: String
147
+ doctype: String
202
148
  label: String
203
149
  width: String
204
150
  align: String
151
+ edit: Boolean
152
+ mask: String
153
+ format: String
154
+ mode: String
155
+ options: JSON
205
156
  required: Boolean
206
157
  readOnly: Boolean
207
- edit: Boolean
208
158
  hidden: Boolean
209
159
  default: JSON
210
- options: JSON
211
- mask: String
212
- precision: Int
213
- scale: Int
214
- mode: String
215
160
  validation: JSON
161
+ cardinality: String
162
+ source: String
216
163
  }
217
164
 
218
165
  type StonecropWorkflowAction {
219
166
  label: String!
220
- handler: String!
221
167
  requiredFields: [String!]
222
168
  allowedStates: [String!]
223
- confirm: Boolean
224
- args: JSON
169
+ nextState: String
170
+ stateless: Boolean
171
+ selfTransition: Boolean
172
+ clientHandler: String
225
173
  }
226
174
 
227
175
  type StonecropWorkflowMeta {
@@ -272,165 +220,165 @@ const Oe = de`
272
220
  extend type Mutation {
273
221
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
274
222
  }
275
- `, Ue = (t = {}) => {
276
- const e = t.debug ? (n, o) => (console.log(`[@stonecrop/graphql-middleware] ${o.text}`, o.values ?? []), n.query(o)) : (n, o) => n.query(o);
277
- return fe((n) => {
278
- const o = n.input?.pgRegistry?.pgExecutors, r = o ? Object.values(o)[0] : void 0;
279
- if (!r)
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 ft((o) => {
226
+ const n = o.input?.pgRegistry?.pgExecutors, s = n ? Object.values(n)[0] : void 0;
227
+ if (!s)
280
228
  throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
281
229
  return {
282
- typeDefs: Oe,
230
+ typeDefs: $t,
283
231
  objects: {
284
232
  Query: {
285
233
  plans: {
286
- stonecropMeta(i, { $doctype: c }) {
287
- return le(c, (a) => I(String(a)) ?? null);
234
+ stonecropMeta(l, { $doctype: f }) {
235
+ return ut(f, (y) => T(String(y)) ?? null);
288
236
  },
289
237
  stonecropAllMeta() {
290
- return ae(me());
238
+ return lt(mt());
291
239
  },
292
- stonecropRecord(i, { $doctype: c, $id: a, $options: w }) {
240
+ stonecropRecord(l, { $doctype: f, $id: y, $options: M }) {
293
241
  return X(
294
- r,
295
- Q({ doctype: c, id: a, options: w }),
296
- async (b, u) => {
297
- const g = /* @__PURE__ */ new Map();
298
- for (let s = 0; s < u.length; s++) {
299
- const p = String(u[s].doctype);
300
- g.has(p) || g.set(p, []), g.get(p).push(s);
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);
301
249
  }
302
- const m = Array.from({ length: u.length });
303
- for (const [s, p] of g) {
304
- const d = I(s);
305
- if (!d) {
306
- for (const f of p) m[f] = { data: null, doctype: s };
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 };
307
255
  continue;
308
256
  }
309
- const R = Z(d);
257
+ const R = Q(a);
310
258
  if (!R) {
311
- for (const f of p) m[f] = { data: null, doctype: s };
259
+ for (const d of p) h[d] = { data: null, doctype: r };
312
260
  continue;
313
261
  }
314
- const H = x(R.fieldname), k = U(d), D = p.map((f) => String(u[f].id)), { rows: J } = await e(b, {
315
- text: `SELECT ${k} FROM ${B(d.name, t.tables)} WHERE "${H}"::text = ANY($1::text[])`,
316
- values: [D]
317
- }), L = new Map(J.map((f) => [String(f[R.fieldname]), f]));
318
- for (const f of p) {
319
- const C = String(u[f].id), v = L.get(C);
320
- if (!v) {
321
- m[f] = { data: null, doctype: s };
262
+ const b = A(R.fieldname), c = U(a), B = 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: [B]
265
+ }), j = new Map(W.map((d) => [String(d[R.fieldname]), d]));
266
+ for (const d of p) {
267
+ const F = String(u[d].id), N = j.get(F);
268
+ if (!N) {
269
+ h[d] = { data: null, doctype: r };
322
270
  continue;
323
271
  }
324
- const l = { ...v }, y = u[f].options ?? {}, M = y.includeNested === !0, h = Array.isArray(y.includeNested) ? new Set(y.includeNested) : null;
325
- if (d.links)
326
- for (const [S, E] of Object.entries(d.links)) {
327
- const N = E.fetch, W = E.cardinality === "noneOrMany" || E.cardinality === "atLeastOne", q = N?.method ?? (W ? "sync" : "lazy"), G = N?.method === "sync" ? N.limit : W ? 50 : void 0;
328
- if (!(M || (h ? h.has(S) : q === "sync"))) continue;
329
- if (q === "custom" && N?.method === "custom") {
330
- const A = N.handler, O = Me(A);
331
- O && (l[S] = await O(b, l, E));
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 = wt(x);
279
+ O && (i[$] = await O(k, i, E));
332
280
  continue;
333
281
  }
334
- if (q !== "sync" && !h?.has(S)) continue;
335
- const j = I(E.target);
336
- if (!j) continue;
337
- const K = U(j);
338
- if (W) {
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) {
339
287
  if (!E.backlink) continue;
340
- const A = x(E.backlink);
341
- let O = `SELECT ${K} FROM ${B(j.name, t.tables)} WHERE "${A}"::text = $1`;
342
- const P = [C];
343
- G != null && (O += " LIMIT $2", P.push(G));
344
- const { rows: _ } = await e(b, {
288
+ const x = A(E.backlink);
289
+ let O = `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${x}"::text = $1`;
290
+ const P = [F];
291
+ Y != null && (O += " LIMIT $2", P.push(Y));
292
+ const { rows: _ } = await e(k, {
345
293
  text: O,
346
294
  values: P
347
295
  });
348
- l[S] = _;
296
+ i[$] = _;
349
297
  } else {
350
298
  if (!E.fieldname) continue;
351
- const A = l[E.fieldname];
352
- if (A == null) {
353
- l[S] = null;
299
+ const x = i[E.fieldname];
300
+ if (x == null) {
301
+ i[$] = null;
354
302
  continue;
355
303
  }
356
- const O = Z(j);
304
+ const O = Q(L);
357
305
  if (!O) continue;
358
- const P = x(O.fieldname), { rows: _ } = await e(b, {
359
- text: `SELECT ${K} FROM ${B(j.name, t.tables)} WHERE "${P}" = $1`,
360
- values: [A]
306
+ const P = A(O.fieldname), { rows: _ } = await e(k, {
307
+ text: `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${P}" = $1`,
308
+ values: [x]
361
309
  });
362
- l[S] = _[0] ?? null;
310
+ i[$] = _[0] ?? null;
363
311
  }
364
312
  }
365
- const F = h && d.links ? [...h].filter((S) => !(S in d.links)) : void 0;
366
- m[f] = {
367
- data: l,
368
- doctype: s,
369
- unknownLinks: F?.length ? F : void 0
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
370
318
  };
371
319
  }
372
320
  }
373
- return m;
321
+ return h;
374
322
  }
375
323
  );
376
324
  },
377
- stonecropRecords(i, { $doctype: c, $filters: a, $orderBy: w, $limit: b, $offset: u }) {
325
+ stonecropRecords(l, { $doctype: f, $filters: y, $orderBy: M, $limit: k, $offset: u }) {
378
326
  return X(
379
- r,
380
- Q({
381
- doctype: c,
382
- filters: a,
383
- orderBy: w,
384
- limit: b,
327
+ s,
328
+ q({
329
+ doctype: f,
330
+ filters: y,
331
+ orderBy: M,
332
+ limit: k,
385
333
  offset: u
386
334
  }),
387
- async (g, m) => await Promise.all(
388
- m.map(async (s) => {
389
- const p = String(s.doctype), d = I(p);
390
- if (!d)
335
+ async (S, h) => await Promise.all(
336
+ h.map(async (r) => {
337
+ const p = String(r.doctype), a = T(p);
338
+ if (!a)
391
339
  return { data: [], doctype: p, count: 0 };
392
- const R = new Set(z(d.fields).map((l) => l.fieldname)), H = U(d), k = [], D = [];
393
- if (s.filters != null)
394
- for (const [l, y] of Object.entries(s.filters)) {
395
- if (!R.has(l))
396
- throw new Error(`Unknown filter field: ${l} for doctype ${d.name}`);
397
- k.push(y), D.push(`"${x(l)}" = $${k.length}`);
340
+ const R = new Set(K(a.fields).map((i) => i.fieldname)), b = U(a), c = [], B = [];
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), B.push(`"${A(i)}" = $${c.length}`);
398
346
  }
399
- const J = D.length > 0 ? ` WHERE ${D.join(" AND ")}` : "";
400
- let L = "";
401
- if (s.orderBy != null) {
402
- if (typeof s.orderBy != "string")
403
- throw new Error(`Invalid orderBy: expected string, got ${typeof s.orderBy}`);
404
- const l = s.orderBy, y = l.lastIndexOf("_");
405
- if (y <= 0)
406
- throw new Error(`Invalid orderBy format: "${l}". Expected FIELD_ASC or FIELD_DESC`);
407
- const M = l.slice(y + 1).toUpperCase();
408
- if (M !== "ASC" && M !== "DESC")
409
- throw new Error(`Invalid orderBy direction: "${M}". Must be ASC or DESC`);
410
- const h = l.slice(0, y);
411
- if (!R.has(h))
412
- throw new Error(`Unknown orderBy field: "${h}" for doctype ${d.name}`);
413
- L = ` ORDER BY "${x(h)}" ${M}`;
347
+ const W = B.length > 0 ? ` WHERE ${B.join(" AND ")}` : "";
348
+ let j = "";
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
+ j = ` ORDER BY "${A(m)}" ${v}`;
414
362
  }
415
- let f = "";
416
- s.limit != null && (k.push(s.limit), f += ` LIMIT $${k.length}`), s.offset != null && (k.push(s.offset), f += ` OFFSET $${k.length}`);
417
- const { rows: C } = await e(g, {
418
- text: `SELECT ${H} FROM ${B(d.name, t.tables)}${J}${L}${f}`,
419
- values: k
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: F } = await e(S, {
366
+ text: `SELECT ${b} FROM ${C(a.name, t.tables)}${W}${j}${d}`,
367
+ values: c
420
368
  });
421
- let v = C.length;
422
- if (s.limit != null || s.offset != null) {
423
- const l = [], y = [];
424
- if (s.filters != null)
425
- for (const [F, S] of Object.entries(s.filters))
426
- R.has(F) && (l.push(S), y.push(`"${x(F)}" = $${l.length}`));
427
- const M = y.length > 0 ? ` WHERE ${y.join(" AND ")}` : "", { rows: h } = await e(g, {
428
- text: `SELECT COUNT(*) AS row_count FROM ${B(d.name, t.tables)}${M}`,
429
- values: l
369
+ let N = F.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
430
378
  });
431
- v = parseInt(h[0]?.row_count ?? "0", 10);
379
+ N = parseInt(m[0]?.row_count ?? "0", 10);
432
380
  }
433
- return { data: C, doctype: p, count: v };
381
+ return { data: F, doctype: p, count: N };
434
382
  })
435
383
  )
436
384
  );
@@ -439,40 +387,55 @@ const Oe = de`
439
387
  },
440
388
  Mutation: {
441
389
  plans: {
442
- stonecropAction(i, { $doctype: c, $action: a, $args: w }) {
443
- return ce(
444
- r,
445
- Q({ doctype: c, action: a, actionArgs: w }),
446
- async (b, u) => {
447
- const g = I(String(u.doctype));
448
- if (!g)
390
+ stonecropAction(l, { $doctype: f, $action: y, $args: M }) {
391
+ return ct(
392
+ s,
393
+ q({ doctype: f, action: y, actionArgs: M }),
394
+ async (k, u) => {
395
+ const S = T(String(u.doctype));
396
+ if (!S)
449
397
  return {
450
398
  success: !1,
451
399
  data: null,
452
400
  error: `Unknown doctype: ${u.doctype}`
453
401
  };
454
- const m = g.workflow?.actions?.[u.action];
455
- if (!m)
402
+ const h = S.workflow?.actions?.[u.action];
403
+ if (!h)
456
404
  return {
457
405
  success: !1,
458
406
  data: null,
459
407
  error: `Unknown action: ${u.action} on ${u.doctype}`
460
408
  };
461
- const s = Se(m.handler);
462
- if (!s)
409
+ const r = Q(S);
410
+ if (!r)
463
411
  return {
464
412
  success: !1,
465
413
  data: null,
466
- error: `Handler not registered: ${m.handler}`
414
+ error: `No primary key for doctype: ${u.doctype}`
467
415
  };
468
- const p = { doctype: g, pgClient: b };
416
+ const p = A(r.fieldname), a = C(S.name, t.tables), b = (Array.isArray(u.actionArgs) ? u.actionArgs : [])[0]?.id;
469
417
  try {
470
- return { success: !0, data: await s(u.actionArgs ?? [], p), error: null };
471
- } catch (d) {
418
+ return await ht(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
+ }
433
+ });
434
+ } catch (c) {
472
435
  return {
473
436
  success: !1,
474
437
  data: null,
475
- error: d instanceof Error ? d.message : String(d)
438
+ error: c instanceof Error ? c.message : String(c)
476
439
  };
477
440
  }
478
441
  }
@@ -484,93 +447,90 @@ const Oe = de`
484
447
  };
485
448
  });
486
449
  };
487
- function z(t) {
450
+ function K(t) {
488
451
  const e = [];
489
- for (const n of t)
490
- n.kind === "fieldset" ? e.push(...z(n.schema)) : e.push(n);
452
+ for (const o of t)
453
+ o.kind === "fieldset" ? e.push(...K(o.schema)) : e.push(o);
491
454
  return e;
492
455
  }
493
- function Re(t, e) {
494
- const n = [];
495
- for (const o of z(t)) {
496
- if (o.kind !== "field" || o.fieldtype === "Display" || o.fieldtype === "Link" && e.has(o.fieldname)) continue;
497
- const r = x(o.fieldname);
498
- n.push(r !== o.fieldname ? `"${r}" AS "${o.fieldname}"` : `"${o.fieldname}"`);
456
+ function kt(t, e) {
457
+ 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 && at(s, n.component) !== "inline") continue;
462
+ const l = A(n.fieldname);
463
+ o.push(l !== n.fieldname ? `"${l}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
499
464
  }
500
- return n;
465
+ return o;
501
466
  }
502
467
  function U(t) {
503
- const e = /* @__PURE__ */ new Set();
468
+ const e = /* @__PURE__ */ new Map();
504
469
  if (t.links)
505
- for (const [n, o] of Object.entries(t.links))
506
- e.add(o.fieldname ?? n);
507
- return Re(t.fields, e).join(", ");
470
+ for (const [o, n] of Object.entries(t.links))
471
+ e.set(n.fieldname ?? o, n);
472
+ return kt(t.fields, e).join(", ");
508
473
  }
509
- function Z(t) {
510
- return t.fields.find((e) => e.kind === "field" && e.fieldtype === "PrimaryKey");
474
+ function Q(t) {
475
+ return t.fields.find((e) => e.kind === "field" && !!e.primaryKey);
511
476
  }
512
- function B(t, e) {
513
- const n = e?.[t] ?? se(t), o = n.indexOf(".");
514
- return o > 0 ? `"${n.slice(0, o)}"."${n.slice(o + 1)}"` : `"${n}"`;
477
+ function C(t, e) {
478
+ const o = e?.[t] ?? it(t), n = o.indexOf(".");
479
+ return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
515
480
  }
516
- const Ve = (t = {}) => {
517
- const { logPlans: e = !0, logTiming: n = !1 } = t, o = (r, i) => ({
518
- plan: (c) => {
519
- e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${i}`);
520
- const a = n ? Date.now() : 0, w = c();
521
- return n && console.log(
522
- `[@stonecrop/graphql-middleware] Plan built for ${r}.${i} in ${Date.now() - a}ms`
523
- ), w;
481
+ const Pt = (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();
486
+ return o && console.log(
487
+ `[@stonecrop/graphql-middleware] Plan built for ${s}.${l} in ${Date.now() - y}ms`
488
+ ), M;
524
489
  }
525
490
  });
526
- return ue({
491
+ return pt({
527
492
  Query: {
528
- stonecropRecord: o("Query", "stonecropRecord"),
529
- stonecropRecords: o("Query", "stonecropRecords"),
530
- stonecropMeta: o("Query", "stonecropMeta"),
531
- stonecropAllMeta: o("Query", "stonecropAllMeta")
493
+ stonecropRecord: n("Query", "stonecropRecord"),
494
+ stonecropRecords: n("Query", "stonecropRecords"),
495
+ stonecropMeta: n("Query", "stonecropMeta"),
496
+ stonecropAllMeta: n("Query", "stonecropAllMeta")
532
497
  },
533
498
  Mutation: {
534
- stonecropAction: o("Mutation", "stonecropAction")
499
+ stonecropAction: n("Mutation", "stonecropAction")
535
500
  }
536
501
  });
537
- }, xe = {
502
+ }, Et = {
538
503
  name: "StonecropFieldCasingPlugin",
539
504
  version: "0.0.0",
540
505
  inflection: {
541
506
  replace: {
542
- attribute(t, e, n) {
543
- return this.upperCamelCase(this._attributeName(n));
507
+ attribute(t, e, o) {
508
+ return this.upperCamelCase(this._attributeName(o));
544
509
  }
545
510
  }
546
511
  }
547
- }, Ae = (t) => ({
548
- extends: [pe],
549
- plugins: t?.fieldCasing === "pascal" ? [xe] : []
550
- }), Ye = Ae();
512
+ }, Mt = (t) => ({
513
+ extends: [gt],
514
+ plugins: t?.fieldCasing === "pascal" ? [Et] : []
515
+ }), Wt = Mt();
551
516
  export {
552
517
  V as DoctypeValidationError,
553
- Ye as StonecropPreset,
554
- be as builtinHandlers,
555
- Qe as clearFetchHandlers,
556
- We as clearHandlers,
557
- Te as clearRegistry,
558
- Ve as createDebugPlugin,
559
- Ue as createStonecropPlugin,
560
- Ae as createStonecropPreset,
561
- me as getAllMeta,
562
- Me as getFetchHandler,
563
- Se as getHandler,
564
- I as getMeta,
565
- Je as hasHandler,
566
- Pe as hasMeta,
567
- ye as loadDoctypes,
568
- Le as loadDoctypesFromObject,
569
- Ke as makePgService,
570
- qe as registerBuiltinHandlers,
571
- _e as registerFetchHandler,
572
- he as registerHandler,
573
- Oe as typeDefs,
574
- He as validateReferences
518
+ Wt as StonecropPreset,
519
+ ht as applyGuardedTransition,
520
+ Tt as clearFetchHandlers,
521
+ It as clearRegistry,
522
+ Pt as createDebugPlugin,
523
+ jt as createStonecropPlugin,
524
+ Mt as createStonecropPreset,
525
+ mt as getAllMeta,
526
+ wt as getFetchHandler,
527
+ T as getMeta,
528
+ Nt as hasMeta,
529
+ yt as loadDoctypes,
530
+ Ft as loadDoctypesFromObject,
531
+ _t as makePgService,
532
+ Lt as registerFetchHandler,
533
+ $t as typeDefs,
534
+ Dt as validateReferences
575
535
  };
576
536
  //# sourceMappingURL=index.js.map