@stonecrop/graphql-middleware 0.12.7 → 0.13.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,131 +1,133 @@
1
- import { readdirSync as W, statSync as _, readFileSync as U } from "node:fs";
2
- import { join as H } from "node:path";
3
- import { validateDoctype as E, parseDoctype as j, toPascalCase as I, snakeToCamel as F } from "@stonecrop/schema";
4
- import { loadOne as M, object as O, constant as P, lambda as Q } from "postgraphile/grafast";
5
- import { gql as V, extendSchema as z } from "postgraphile/utils";
6
- import C from "pluralize";
7
- const k = /* @__PURE__ */ new Map();
8
- class R extends Error {
9
- constructor(t, n) {
1
+ import { readdirSync as G, statSync as K, readFileSync as X } from "node:fs";
2
+ import { join as Z } from "node:path";
3
+ import { validateDoctype as V, parseDoctype as Y } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as ee, loadOneWithPgClient as U } from "@dataplan/pg";
5
+ import { object as J, constant as te, lambda as ne } from "postgraphile/grafast";
6
+ import { gql as oe, extendSchema as re, wrapPlans as ie } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as se } from "postgraphile/presets/amber";
8
+ import { makePgService as qe } from "postgraphile/adaptors/pg";
9
+ const b = /* @__PURE__ */ new Map();
10
+ class T extends Error {
11
+ constructor(e, n) {
10
12
  const i = n.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
11
13
  `);
12
- super(`Invalid doctype definition in ${t}:
13
- ${i}`), this.file = t, this.errors = n, this.name = "DoctypeValidationError";
14
+ super(`Invalid doctype definition in ${e}:
15
+ ${i}`), this.file = e, this.errors = n, this.name = "DoctypeValidationError";
14
16
  }
15
17
  file;
16
18
  errors;
17
19
  }
18
- function G(e, t = {}) {
19
- const n = W(e);
20
+ function ce(t, e = {}) {
21
+ const n = G(t);
20
22
  for (const i of n) {
21
- const r = H(e, i);
22
- _(r).isDirectory() ? G(r, t) : i.endsWith(".json") && Y(r, t);
23
+ const r = Z(t, i);
24
+ K(r).isDirectory() ? ce(r, e) : i.endsWith(".json") && ae(r, e);
23
25
  }
24
26
  }
25
- function Y(e, t) {
26
- const n = U(e, "utf-8");
27
+ function ae(t, e) {
28
+ const n = X(t, "utf-8");
27
29
  let i;
28
30
  try {
29
31
  i = JSON.parse(n);
30
- } catch (s) {
32
+ } catch (a) {
31
33
  const c = {
32
34
  path: [],
33
- message: `Invalid JSON: ${s instanceof Error ? s.message : String(s)}`
35
+ message: `Invalid JSON: ${a instanceof Error ? a.message : String(a)}`
34
36
  };
35
- if (t.continueOnError) {
36
- t.onError?.(e, [c]);
37
+ if (e.continueOnError) {
38
+ e.onError?.(t, [c]);
37
39
  return;
38
40
  }
39
- throw new R(e, [c]);
41
+ throw new T(t, [c]);
40
42
  }
41
- const r = E(i);
43
+ const r = V(i);
42
44
  if (!r.success) {
43
- if (t.continueOnError) {
44
- t.onError?.(e, r.errors);
45
+ if (e.continueOnError) {
46
+ e.onError?.(t, r.errors);
45
47
  return;
46
48
  }
47
- throw new R(e, r.errors);
49
+ throw new T(t, r.errors);
48
50
  }
49
- const o = j(i);
50
- k.set(o.name, o);
51
+ const o = Y(i);
52
+ b.set(o.name, o);
51
53
  }
52
- function Me(e, t = {}) {
53
- for (const [n, i] of Object.entries(e)) {
54
- const r = { ...i, name: n }, o = E(r);
54
+ function xe(t, e = {}) {
55
+ for (const [n, i] of Object.entries(t)) {
56
+ const r = { ...i, name: n }, o = V(r);
55
57
  if (!o.success) {
56
- if (t.continueOnError) {
57
- t.onError?.(n, o.errors);
58
+ if (e.continueOnError) {
59
+ e.onError?.(n, o.errors);
58
60
  continue;
59
61
  }
60
- throw new R(n, o.errors);
62
+ throw new T(n, o.errors);
61
63
  }
62
- const s = j(r);
63
- k.set(s.name, s);
64
+ const a = Y(r);
65
+ b.set(a.name, a);
64
66
  }
65
67
  }
66
- function $(e) {
67
- const t = k.get(e);
68
- if (t) return t;
69
- for (const n of k.values())
70
- if (n.slug === e) return n;
68
+ function v(t) {
69
+ const e = b.get(t);
70
+ if (e) return e;
71
+ for (const n of b.values())
72
+ if (n.slug === t) return n;
71
73
  }
72
- function K() {
73
- return Array.from(k.values());
74
+ function le() {
75
+ return Array.from(b.values());
74
76
  }
75
- function Oe(e) {
76
- return k.has(e);
77
+ function Ae(t) {
78
+ return b.has(t);
77
79
  }
78
80
  function Fe() {
79
- k.clear();
81
+ b.clear();
80
82
  }
81
- function Re() {
82
- const e = [];
83
- for (const t of k.values()) {
84
- t.inherits && !k.has(t.inherits) && e.push({
85
- path: [t.name, "inherits"],
86
- message: `References unknown doctype: ${t.inherits}`
83
+ function ve() {
84
+ const t = [];
85
+ for (const e of b.values()) {
86
+ e.inherits && !b.has(e.inherits) && t.push({
87
+ path: [e.name, "inherits"],
88
+ message: `References unknown doctype: ${e.inherits}`
87
89
  });
88
- for (const n of t.fields)
89
- n.fieldtype === "Link" && typeof n.options == "string" && (k.has(n.options) || e.push({
90
- path: [t.name, "fields", n.fieldname, "options"],
90
+ for (const n of e.fields)
91
+ n.fieldtype === "Link" && typeof n.options == "string" && (b.has(n.options) || t.push({
92
+ path: [e.name, "fields", n.fieldname, "options"],
91
93
  message: `Link references unknown doctype: ${n.options}`
92
94
  }));
93
95
  }
94
- return e;
96
+ return t;
95
97
  }
96
- const w = /* @__PURE__ */ new Map();
97
- function X(e, t) {
98
- w.set(e, t);
98
+ const I = /* @__PURE__ */ new Map();
99
+ function de(t, e) {
100
+ I.set(t, e);
99
101
  }
100
- function Z(e) {
101
- return w.get(e);
102
+ function fe(t) {
103
+ return I.get(t);
102
104
  }
103
- function Ae(e) {
104
- return w.has(e);
105
+ function Ce(t) {
106
+ return I.has(t);
105
107
  }
106
- function De() {
107
- w.clear();
108
+ function je() {
109
+ I.clear();
108
110
  }
109
- const ee = async (e, t) => {
110
- const [n] = e, { doctype: i } = t, r = [];
111
+ const ue = async (t, e) => {
112
+ const [n] = t, { doctype: i } = e, r = [];
111
113
  for (const o of i.fields)
112
114
  o.required && (n[o.fieldname] === void 0 || n[o.fieldname] === null) && r.push(o.label ?? o.fieldname);
113
115
  if (r.length > 0)
114
116
  throw new Error(`Missing required fields: ${r.join(", ")}`);
115
117
  return { valid: !0 };
116
- }, te = async (e, t) => {
117
- const [n] = e, { doctype: i } = t, r = [];
118
+ }, pe = async (t, e) => {
119
+ const [n] = t, { doctype: i } = e, r = [];
118
120
  for (const o of i.fields) {
119
- const s = n[o.fieldname];
120
- if (s == null) continue;
121
- const c = ne(o, s);
121
+ const a = n[o.fieldname];
122
+ if (a == null) continue;
123
+ const c = ye(o, a);
122
124
  c && r.push(c);
123
125
  }
124
126
  if (i.links)
125
- for (const [o, s] of Object.entries(i.links)) {
127
+ for (const [o, a] of Object.entries(i.links)) {
126
128
  const c = n[o];
127
129
  if (c == null) continue;
128
- s.cardinality === "noneOrMany" || s.cardinality === "atLeastOne" ? Array.isArray(c) || r.push(`${o}: expected array, got ${typeof c}`) : (typeof c != "object" || Array.isArray(c)) && r.push(`${o}: expected object, got ${typeof c}`);
130
+ a.cardinality === "noneOrMany" || a.cardinality === "atLeastOne" ? Array.isArray(c) || r.push(`${o}: expected array, got ${typeof c}`) : (typeof c != "object" || Array.isArray(c)) && r.push(`${o}: expected object, got ${typeof c}`);
129
131
  }
130
132
  if (r.length > 0)
131
133
  throw new Error(`Field type validation failed:
@@ -133,54 +135,64 @@ ${r.join(`
133
135
  `)}`);
134
136
  return { valid: !0 };
135
137
  };
136
- function ne(e, t) {
137
- const { fieldname: n, fieldtype: i } = e;
138
+ function ye(t, e) {
139
+ const { fieldname: n, fieldtype: i } = t;
138
140
  switch (i) {
139
141
  case "Int":
140
- if (typeof t != "number" || !Number.isInteger(t))
141
- return `${n}: expected integer, got ${typeof t}`;
142
+ if (typeof e != "number" || !Number.isInteger(e))
143
+ return `${n}: expected integer, got ${typeof e}`;
142
144
  break;
143
145
  case "Float":
144
146
  case "Decimal":
145
147
  case "Currency":
146
148
  case "Quantity":
147
- if (typeof t != "number" && typeof t != "string")
148
- return `${n}: expected number, got ${typeof t}`;
149
+ if (typeof e != "number" && typeof e != "string")
150
+ return `${n}: expected number, got ${typeof e}`;
149
151
  break;
150
152
  case "Check":
151
- if (typeof t != "boolean")
152
- return `${n}: expected boolean, got ${typeof t}`;
153
+ if (typeof e != "boolean")
154
+ return `${n}: expected boolean, got ${typeof e}`;
153
155
  break;
154
156
  case "Data":
155
157
  case "Text":
156
158
  case "Code":
157
159
  case "Link":
158
- if (typeof t != "string")
159
- return `${n}: expected string, got ${typeof t}`;
160
+ if (typeof e != "string")
161
+ return `${n}: expected string, got ${typeof e}`;
160
162
  break;
161
163
  case "Date":
162
164
  case "Time":
163
165
  case "Datetime":
164
- if (typeof t != "string" && !(t instanceof Date))
165
- return `${n}: expected date string or Date, got ${typeof t}`;
166
+ if (typeof e != "string" && !(e instanceof Date))
167
+ return `${n}: expected date string or Date, got ${typeof e}`;
166
168
  break;
167
169
  case "JSON":
168
- if (typeof t != "object")
169
- return `${n}: expected object, got ${typeof t}`;
170
+ if (typeof e != "object")
171
+ return `${n}: expected object, got ${typeof e}`;
170
172
  break;
171
173
  }
172
174
  return null;
173
175
  }
174
- const re = async () => ({ ok: !0 }), oe = {
175
- validateRequiredFields: ee,
176
- validateFieldTypes: te,
177
- noop: re
176
+ const ge = async () => ({ ok: !0 }), me = {
177
+ validateRequiredFields: ue,
178
+ validateFieldTypes: pe,
179
+ noop: ge
178
180
  };
179
- function ve() {
180
- for (const [e, t] of Object.entries(oe))
181
- X(e, t);
181
+ function Ie() {
182
+ for (const [t, e] of Object.entries(me))
183
+ de(t, e);
184
+ }
185
+ const q = /* @__PURE__ */ new Map();
186
+ function Be(t, e) {
187
+ q.set(t, e);
188
+ }
189
+ function he(t) {
190
+ return q.get(t);
191
+ }
192
+ function Le() {
193
+ q.clear();
182
194
  }
183
- const ie = V`
195
+ const Se = oe`
184
196
  type StonecropFieldMeta {
185
197
  fieldname: String!
186
198
  fieldtype: String!
@@ -259,345 +271,277 @@ const ie = V`
259
271
  extend type Mutation {
260
272
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
261
273
  }
262
- `, xe = (e) => {
263
- const t = e.inflection?.recordFieldName ?? ce, n = e.inflection?.connectionFieldName ?? se, i = e.inflection?.orderByTypeName ?? ae, r = e.inflection?.recordArgName ?? le, o = e.inflection?.recordArgType ?? de, s = e.inflection?.reverseConnectionName ?? A;
264
- return z(() => ({
265
- typeDefs: ie,
266
- objects: {
267
- Query: {
268
- plans: {
269
- stonecropMeta(c, { $doctype: a }) {
270
- return Q(a, (p) => $(p) ?? null);
271
- },
272
- stonecropAllMeta() {
273
- return P(K());
274
- },
275
- stonecropRecord(c, { $doctype: a, $id: p, $options: u }) {
276
- return M(
277
- O({ doctype: a, id: p, options: u }),
278
- async (l) => await Promise.all(
279
- l.map(async (d) => {
280
- const f = $(d.doctype);
281
- if (!f)
282
- throw new Error(`Unknown doctype: ${d.doctype}`);
283
- if (!f.tableName)
284
- throw new Error(`Doctype ${d.doctype} has no table mapping`);
285
- const y = d.options ?? {}, m = ye(
286
- f,
287
- t,
288
- r,
289
- o,
290
- $,
291
- y.includeNested ? {
292
- includeNested: y.includeNested,
293
- maxDepth: y.maxDepth
294
- } : void 0,
295
- s
296
- ), g = await e.executor.query(m, {
297
- [r(f.tableName)]: d.id
298
- });
299
- let h = ge({ result: g, meta: f, recordFieldName: t });
300
- y.includeNested && h && f.links && (h = me({
301
- record: h,
302
- meta: f,
303
- getMeta: $,
304
- reverseConnectionNameFn: s
305
- }));
306
- const S = Array.isArray(y.includeNested) && f.links ? y.includeNested.filter((N) => !(N in f.links)) : void 0;
307
- return {
308
- data: h,
309
- doctype: d.doctype,
310
- ...S ? { unknownLinks: S } : {}
311
- };
312
- })
313
- )
314
- );
315
- },
316
- stonecropRecords(c, { $doctype: a, $filters: p, $orderBy: u, $limit: l, $offset: d, $options: f }) {
317
- return M(
318
- O({
319
- doctype: a,
320
- filters: p,
321
- orderBy: u,
322
- limit: l,
323
- offset: d,
324
- options: f
325
- }),
326
- async (y) => await Promise.all(
327
- y.map(async (m) => {
328
- const g = $(m.doctype);
329
- if (!g)
330
- throw new Error(`Unknown doctype: ${m.doctype}`);
331
- if (!g.tableName)
332
- throw new Error(`Doctype ${m.doctype} has no table mapping`);
333
- const h = pe(
334
- g,
335
- {
336
- limit: m.limit,
337
- offset: m.offset,
338
- orderBy: m.orderBy
339
- },
340
- n,
341
- i
342
- ), S = await e.executor.query(h, {
343
- limit: m.limit,
344
- offset: m.offset,
345
- orderBy: m.orderBy
346
- }), N = he({ result: S, meta: g, connectionFieldName: n });
347
- return {
348
- data: N,
349
- doctype: m.doctype,
350
- count: N.length
351
- };
352
- })
353
- )
354
- );
274
+ `, Pe = (t = {}) => {
275
+ const e = t.pkField ?? "id", n = t.debug ? (i, r) => (console.log(`[@stonecrop/graphql-middleware] ${r.text}`, r.values ?? []), i.query(r)) : (i, r) => i.query(r);
276
+ return re((i) => {
277
+ const r = i.input?.pgRegistry?.pgExecutors, o = r ? Object.values(r)[0] : void 0;
278
+ if (!o)
279
+ throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
280
+ return {
281
+ typeDefs: Se,
282
+ objects: {
283
+ Query: {
284
+ plans: {
285
+ stonecropMeta(a, { $doctype: c }) {
286
+ return ne(c, ($) => v($) ?? null);
287
+ },
288
+ stonecropAllMeta() {
289
+ return te(le());
290
+ },
291
+ stonecropRecord(a, { $doctype: c, $id: $, $options: D }) {
292
+ return U(
293
+ o,
294
+ J({ doctype: c, id: $, options: D }),
295
+ async (M, u) => {
296
+ const g = /* @__PURE__ */ new Map();
297
+ for (let s = 0; s < u.length; s++) {
298
+ const d = u[s].doctype;
299
+ g.has(d) || g.set(d, []), g.get(d).push(s);
300
+ }
301
+ const w = new Array(u.length);
302
+ for (const [s, d] of g) {
303
+ const f = v(s);
304
+ if (!f?.tableName) {
305
+ for (const p of d) w[p] = { data: null, doctype: s };
306
+ continue;
307
+ }
308
+ const B = W(f, e), E = d.map((p) => u[p].id), { rows: A } = await n(M, {
309
+ text: `SELECT ${B} FROM "${f.tableName}" WHERE "${e}"::text = ANY($1::text[])`,
310
+ values: [E]
311
+ }), L = new Map(A.map((p) => [String(p[e]), p]));
312
+ for (const p of d) {
313
+ const x = u[p].id, F = L.get(x);
314
+ if (!F) {
315
+ w[p] = { data: null, doctype: s };
316
+ continue;
317
+ }
318
+ const k = { ...F }, l = u[p].options ?? {}, m = l.includeNested === !0, y = Array.isArray(l.includeNested) ? new Set(l.includeNested) : null;
319
+ if (f.links)
320
+ for (const [h, S] of Object.entries(f.links)) {
321
+ const C = S.fetch, P = S.cardinality === "noneOrMany" || S.cardinality === "atLeastOne", H = C?.method ?? (P ? "sync" : "lazy"), _ = C?.method === "sync" ? C.limit : P ? 50 : void 0;
322
+ if (!(m || (y ? y.has(h) : H === "sync"))) continue;
323
+ if (H === "custom") {
324
+ const R = C.handler, N = he(R);
325
+ N && (k[h] = await N(M, k, S));
326
+ continue;
327
+ }
328
+ if (H !== "sync" && !y?.has(h)) continue;
329
+ const j = v(S.target);
330
+ if (!j?.tableName) continue;
331
+ const Q = W(j, e);
332
+ if (P) {
333
+ if (!S.backlink) continue;
334
+ let R = `SELECT ${Q} FROM "${j.tableName}" WHERE "${S.backlink}"::text = $1`;
335
+ const N = [x];
336
+ _ != null && (R += " LIMIT $2", N.push(_));
337
+ const { rows: z } = await n(M, {
338
+ text: R,
339
+ values: N
340
+ });
341
+ k[h] = z;
342
+ } else {
343
+ if (!S.fieldname) continue;
344
+ const R = k[S.fieldname];
345
+ if (R == null) {
346
+ k[h] = null;
347
+ continue;
348
+ }
349
+ const { rows: N } = await n(M, {
350
+ text: `SELECT ${Q} FROM "${j.tableName}" WHERE "${e}" = $1`,
351
+ values: [R]
352
+ });
353
+ k[h] = N[0] ?? null;
354
+ }
355
+ }
356
+ const O = y && f.links ? [...y].filter((h) => !(h in f.links)) : void 0;
357
+ w[p] = {
358
+ data: k,
359
+ doctype: s,
360
+ unknownLinks: O?.length ? O : void 0
361
+ };
362
+ }
363
+ }
364
+ return w;
365
+ }
366
+ );
367
+ },
368
+ stonecropRecords(a, { $doctype: c, $filters: $, $orderBy: D, $limit: M, $offset: u }) {
369
+ return U(
370
+ o,
371
+ J({
372
+ doctype: c,
373
+ filters: $,
374
+ orderBy: D,
375
+ limit: M,
376
+ offset: u
377
+ }),
378
+ async (g, w) => await Promise.all(
379
+ w.map(async (s) => {
380
+ const d = v(s.doctype);
381
+ if (!d?.tableName)
382
+ return { data: [], doctype: s.doctype, count: 0 };
383
+ const f = new Set(d.fields.map((l) => l.fieldname)), B = W(d, e), E = [], A = [];
384
+ if (s.filters != null)
385
+ for (const [l, m] of Object.entries(s.filters)) {
386
+ if (!f.has(l))
387
+ throw new Error(`Unknown filter field: ${l} for doctype ${d.name}`);
388
+ E.push(m), A.push(`"${l}" = $${E.length}`);
389
+ }
390
+ const L = A.length > 0 ? ` WHERE ${A.join(" AND ")}` : "";
391
+ let p = "";
392
+ if (s.orderBy != null) {
393
+ const l = s.orderBy, m = l.lastIndexOf("_");
394
+ if (m <= 0)
395
+ throw new Error(`Invalid orderBy format: "${l}". Expected FIELD_ASC or FIELD_DESC`);
396
+ const y = l.slice(m + 1).toUpperCase();
397
+ if (y !== "ASC" && y !== "DESC")
398
+ throw new Error(`Invalid orderBy direction: "${y}". Must be ASC or DESC`);
399
+ const O = l.slice(0, m);
400
+ if (!f.has(O))
401
+ throw new Error(`Unknown orderBy field: "${O}" for doctype ${d.name}`);
402
+ p = ` ORDER BY "${O}" ${y}`;
403
+ }
404
+ let x = "";
405
+ s.limit != null && (E.push(s.limit), x += ` LIMIT $${E.length}`), s.offset != null && (E.push(s.offset), x += ` OFFSET $${E.length}`);
406
+ const { rows: F } = await n(g, {
407
+ text: `SELECT ${B} FROM "${d.tableName}"${L}${p}${x}`,
408
+ values: E
409
+ });
410
+ let k = F.length;
411
+ if (s.limit != null || s.offset != null) {
412
+ const l = [], m = [];
413
+ if (s.filters != null)
414
+ for (const [h, S] of Object.entries(s.filters))
415
+ f.has(h) && (l.push(S), m.push(`"${h}" = $${l.length}`));
416
+ const y = m.length > 0 ? ` WHERE ${m.join(" AND ")}` : "", { rows: O } = await n(g, {
417
+ text: `SELECT COUNT(*) AS __count FROM "${d.tableName}"${y}`,
418
+ values: l
419
+ });
420
+ k = parseInt(O[0]?.__count ?? "0", 10);
421
+ }
422
+ return { data: F, doctype: s.doctype, count: k };
423
+ })
424
+ )
425
+ );
426
+ }
355
427
  }
356
- }
357
- },
358
- Mutation: {
359
- plans: {
360
- stonecropAction(c, { $doctype: a, $action: p, $args: u }) {
361
- return M(
362
- O({
363
- doctype: a,
364
- action: p,
365
- actionArgs: u
366
- }),
367
- async (l) => await Promise.all(
368
- l.map(async (d) => {
369
- const f = $(d.doctype);
370
- if (!f)
428
+ },
429
+ Mutation: {
430
+ plans: {
431
+ stonecropAction(a, { $doctype: c, $action: $, $args: D }) {
432
+ return ee(
433
+ o,
434
+ J({ doctype: c, action: $, actionArgs: D }),
435
+ async (M, u) => {
436
+ const g = v(u.doctype);
437
+ if (!g)
371
438
  return {
372
439
  success: !1,
373
440
  data: null,
374
- error: `Unknown doctype: ${d.doctype}`
441
+ error: `Unknown doctype: ${u.doctype}`
375
442
  };
376
- const y = f.workflow?.actions?.[d.action];
377
- if (!y)
443
+ const w = g.workflow?.actions?.[u.action];
444
+ if (!w)
378
445
  return {
379
446
  success: !1,
380
447
  data: null,
381
- error: `Unknown action: ${d.action} on ${d.doctype}`
448
+ error: `Unknown action: ${u.action} on ${u.doctype}`
382
449
  };
383
- const m = y.handler, g = Z(m);
384
- if (!g)
450
+ const s = fe(w.handler);
451
+ if (!s)
385
452
  return {
386
453
  success: !1,
387
454
  data: null,
388
- error: `Handler not registered: ${m}`
455
+ error: `Handler not registered: ${w.handler}`
389
456
  };
390
- const h = {
391
- doctype: f,
392
- executor: e.executor
393
- };
457
+ const d = { doctype: g, pgClient: M };
394
458
  try {
395
- return {
396
- success: !0,
397
- data: await g(d.actionArgs ?? [], h),
398
- error: null
399
- };
400
- } catch (S) {
459
+ return { success: !0, data: await s(u.actionArgs ?? [], d), error: null };
460
+ } catch (f) {
401
461
  return {
402
462
  success: !1,
403
463
  data: null,
404
- error: S instanceof Error ? S.message : String(S)
464
+ error: f instanceof Error ? f.message : String(f)
405
465
  };
406
466
  }
407
- })
408
- )
409
- );
467
+ }
468
+ );
469
+ }
410
470
  }
411
471
  }
412
472
  }
413
- }
414
- }));
473
+ };
474
+ });
415
475
  };
416
- function ce(e) {
417
- const t = C.singular(e);
418
- return `${F(t)}ById`;
419
- }
420
- function se(e) {
421
- return `all${I(e)}`;
422
- }
423
- function ae(e) {
424
- return `${I(e)}OrderBy`;
425
- }
426
- function le(e) {
427
- return "id";
476
+ function W(t, e) {
477
+ const n = /* @__PURE__ */ new Set();
478
+ if (t.links)
479
+ for (const [o, a] of Object.entries(t.links))
480
+ n.add(a.fieldname ?? o);
481
+ const i = [];
482
+ t.fields.some((o) => o.fieldname === e) || i.push(`"${e}"`);
483
+ for (const o of t.fields)
484
+ o.fieldtype !== "Display" && (o.fieldtype === "Link" && n.has(o.fieldname) || i.push(`"${o.fieldname}"`));
485
+ return i.join(", ");
428
486
  }
429
- function de(e) {
430
- return "UUID!";
431
- }
432
- function A(e) {
433
- const t = C.plural(e.target.replace(/-/g, "_")), n = F(t), i = e.backlink || e.doctype, r = i.charAt(0).toUpperCase() + F(i).slice(1);
434
- return `${n}By${r}Id`;
435
- }
436
- function D(e) {
437
- return e === "noneOrMany" || e === "atLeastOne";
438
- }
439
- const T = 50, fe = /* @__PURE__ */ new Set(["Display"]);
440
- function v(e) {
441
- const t = /* @__PURE__ */ new Set();
442
- if (e.links)
443
- for (const [n, i] of Object.entries(e.links))
444
- t.add(i.fieldname ?? n);
445
- return e.fields.filter((n) => !(fe.has(n.fieldtype) || n.fieldtype === "Link" && t.has(n.fieldname))).map((n) => n.fieldname).join(`
446
- `);
447
- }
448
- function q(e) {
449
- return e.fetch !== void 0 ? e.fetch : D(e.cardinality) ? { method: "sync", limit: T } : { method: "lazy" };
450
- }
451
- function ue(e) {
452
- return e.blockWorkflows !== void 0 ? e.blockWorkflows : q(e).method === "sync";
453
- }
454
- function L(e) {
455
- const { links: t, meta: n, includeSet: i, getMeta: r, seen: o, depth: s, maxDepth: c, reverseConnectionNameFn: a } = e;
456
- if (c !== void 0 && s >= c) return "";
457
- const p = [];
458
- for (const [u, l] of Object.entries(t)) {
459
- if (c !== void 0 && s >= c) break;
460
- const d = ue(l), f = l.blockWorkflows === !0;
461
- if (i && !i.has(u) && !f)
462
- continue;
463
- const y = q(l);
464
- if (d === !1 || y.method !== "sync" && !f)
465
- continue;
466
- const g = r(l.target);
467
- if (!g) continue;
468
- const h = o.has(l.target);
469
- h || o.add(l.target);
470
- const S = v(g);
471
- let N = "";
472
- if (!h && g.links && g.tableName && (c === void 0 || s + 1 < c)) {
473
- const b = L({
474
- links: g.links,
475
- meta: g,
476
- includeSet: null,
477
- getMeta: r,
478
- seen: o,
479
- depth: s + 1,
480
- maxDepth: c,
481
- reverseConnectionNameFn: a
482
- });
483
- b && (N = `
484
- ` + b), o.delete(l.target);
487
+ const He = (t = {}) => {
488
+ const { logPlans: e = !0, logTiming: n = !1 } = t, i = (r, o) => ({
489
+ plan: (a) => {
490
+ e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${o}`);
491
+ const c = n ? Date.now() : 0, $ = a();
492
+ return n && console.log(
493
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${o} in ${Date.now() - c}ms`
494
+ ), $;
485
495
  }
486
- const x = S + N;
487
- if (D(l.cardinality)) {
488
- const b = {
489
- doctype: n.slug || n.name,
490
- linkName: u,
491
- backlink: l.backlink,
492
- target: l.target
493
- }, J = a ? a(b) : A(b), B = y.method === "sync" && y.limit !== void 0 ? `first: ${y.limit}` : y.method === "sync" ? `first: ${T}` : "";
494
- p.push(`
495
- ${J}${B ? `(${B})` : ""} {
496
- nodes {
497
- ${x}
498
- }
499
- }`);
500
- } else
501
- p.push(`
502
- ${u} {
503
- ${x}
504
- }`);
505
- }
506
- return p.join("");
507
- }
508
- function ye(e, t, n, i, r, o, s) {
509
- const c = t(e.tableName), a = n(e.tableName), p = i(e.tableName), u = /* @__PURE__ */ new Set([e.slug || e.name]);
510
- let l = v(e);
511
- if (o?.includeNested && e.links) {
512
- const d = Array.isArray(o.includeNested) ? new Set(o.includeNested) : null, f = L({
513
- links: e.links,
514
- meta: e,
515
- includeSet: d,
516
- getMeta: r,
517
- seen: u,
518
- depth: 0,
519
- maxDepth: o.maxDepth,
520
- reverseConnectionNameFn: s
521
- });
522
- f && (l += `
523
- ` + f);
524
- }
525
- return `
526
- query GetRecord($${a}: ${p}) {
527
- ${c}(${a}: $${a}) {
528
- ${l}
529
- }
530
- }
531
- `;
532
- }
533
- function pe(e, t, n, i) {
534
- const r = v(e), o = n(e.tableName), s = i(e.tableName), c = [], a = [];
535
- t.limit && (c.push("$limit: Int"), a.push("first: $limit")), t.offset && (c.push("$offset: Int"), a.push("offset: $offset")), t.orderBy && (c.push(`$orderBy: [${s}!]`), a.push("orderBy: $orderBy"));
536
- const p = c.length > 0 ? `(${c.join(", ")})` : "", u = a.length > 0 ? `(${a.join(", ")})` : "";
537
- return `
538
- query GetRecords${p} {
539
- ${o}${u} {
540
- nodes {
541
- ${r}
542
- }
543
- }
544
- }
545
- `;
546
- }
547
- function me(e) {
548
- const { record: t, meta: n, getMeta: i, reverseConnectionNameFn: r } = e;
549
- if (!n.links) return t;
550
- const o = { ...t };
551
- for (const [s, c] of Object.entries(n.links))
552
- if (D(c.cardinality)) {
553
- if (!i(c.target)) continue;
554
- const u = {
555
- doctype: n.slug || n.name,
556
- linkName: s,
557
- backlink: c.backlink || s,
558
- target: c.target
559
- }, l = r ? r(u) : A(u), d = o[l];
560
- d?.nodes ? (o[s] = d.nodes, delete o[l]) : (o[s] = [], delete o[l]);
496
+ });
497
+ return ie({
498
+ Query: {
499
+ stonecropRecord: i("Query", "stonecropRecord"),
500
+ stonecropRecords: i("Query", "stonecropRecords"),
501
+ stonecropMeta: i("Query", "stonecropMeta"),
502
+ stonecropAllMeta: i("Query", "stonecropAllMeta")
503
+ },
504
+ Mutation: {
505
+ stonecropAction: i("Mutation", "stonecropAction")
561
506
  }
562
- return o;
563
- }
564
- function ge(e) {
565
- const { result: t, meta: n, recordFieldName: i } = e, r = i(n.tableName);
566
- return t[r];
567
- }
568
- function he(e) {
569
- const { result: t, meta: n, connectionFieldName: i } = e, r = i(n.tableName);
570
- return t[r]?.nodes ?? [];
571
- }
507
+ });
508
+ }, $e = {
509
+ name: "StonecropFieldCasingPlugin",
510
+ version: "0.0.0",
511
+ inflection: {
512
+ replace: {
513
+ attribute(t, e, n) {
514
+ return this.upperCamelCase(this._attributeName(n));
515
+ }
516
+ }
517
+ }
518
+ }, we = (t) => ({
519
+ extends: [se],
520
+ plugins: t?.fieldCasing === "pascal" ? [$e] : []
521
+ }), Je = we();
572
522
  export {
573
- R as DoctypeValidationError,
574
- fe as RELATION_FIELDTYPES,
575
- pe as buildListQuery,
576
- ye as buildRecordQuery,
577
- oe as builtinHandlers,
578
- De as clearHandlers,
523
+ T as DoctypeValidationError,
524
+ Je as StonecropPreset,
525
+ me as builtinHandlers,
526
+ Le as clearFetchHandlers,
527
+ je as clearHandlers,
579
528
  Fe as clearRegistry,
580
- xe as createStonecropPlugin,
581
- se as defaultConnectionFieldName,
582
- ae as defaultOrderByTypeName,
583
- le as defaultRecordArgName,
584
- de as defaultRecordArgType,
585
- ce as defaultRecordFieldName,
586
- A as defaultReverseConnectionName,
587
- he as extractListResult,
588
- ge as extractSingleResult,
589
- K as getAllMeta,
590
- Z as getHandler,
591
- $ as getMeta,
592
- Ae as hasHandler,
593
- Oe as hasMeta,
594
- G as loadDoctypes,
595
- Me as loadDoctypesFromObject,
596
- me as mergeNestedResults,
597
- v as queryableFieldNames,
598
- ve as registerBuiltinHandlers,
599
- X as registerHandler,
600
- ie as typeDefs,
601
- Re as validateReferences
529
+ He as createDebugPlugin,
530
+ Pe as createStonecropPlugin,
531
+ we as createStonecropPreset,
532
+ le as getAllMeta,
533
+ he as getFetchHandler,
534
+ fe as getHandler,
535
+ v as getMeta,
536
+ Ce as hasHandler,
537
+ Ae as hasMeta,
538
+ ce as loadDoctypes,
539
+ xe as loadDoctypesFromObject,
540
+ qe as makePgService,
541
+ Ie as registerBuiltinHandlers,
542
+ Be as registerFetchHandler,
543
+ de as registerHandler,
544
+ Se as typeDefs,
545
+ ve as validateReferences
602
546
  };
603
547
  //# sourceMappingURL=index.js.map