@stonecrop/graphql-middleware 0.12.8 → 0.13.1

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) {
10
- const i = n.map((r) => ` ${r.path.join(".")}: ${r.message}`).join(`
1
+ import { readdirSync as te, statSync as ne, readFileSync as oe } from "node:fs";
2
+ import { join as re } from "node:path";
3
+ import { validateDoctype as Z, parseDoctype as ee, camelToSnake as x, pascalToSnake as ie } from "@stonecrop/schema";
4
+ import { sideEffectWithPgClient as se, loadOneWithPgClient as K } from "@dataplan/pg";
5
+ import { object as Q, constant as ce, lambda as ae } from "postgraphile/grafast";
6
+ import { gql as le, extendSchema as de, wrapPlans as fe } from "postgraphile/utils";
7
+ import { PostGraphileAmberPreset as ue } from "postgraphile/presets/amber";
8
+ import { makePgService as ze } from "postgraphile/adaptors/pg";
9
+ const S = /* @__PURE__ */ new Map();
10
+ class V extends Error {
11
+ constructor(e, n) {
12
+ const o = 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
+ ${o}`), 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
- for (const i of n) {
21
- const r = H(e, i);
22
- _(r).isDirectory() ? G(r, t) : i.endsWith(".json") && Y(r, t);
20
+ function pe(t, e = {}) {
21
+ const n = te(t);
22
+ for (const o of n) {
23
+ const r = re(t, o);
24
+ ne(r).isDirectory() ? pe(r, e) : o.endsWith(".json") && ye(r, e);
23
25
  }
24
26
  }
25
- function Y(e, t) {
26
- const n = U(e, "utf-8");
27
- let i;
27
+ function ye(t, e) {
28
+ const n = oe(t, "utf-8");
29
+ let o;
28
30
  try {
29
- i = JSON.parse(n);
30
- } catch (s) {
31
- const c = {
31
+ o = JSON.parse(n);
32
+ } catch (c) {
33
+ const a = {
32
34
  path: [],
33
- message: `Invalid JSON: ${s instanceof Error ? s.message : String(s)}`
35
+ message: `Invalid JSON: ${c instanceof Error ? c.message : String(c)}`
34
36
  };
35
- if (t.continueOnError) {
36
- t.onError?.(e, [c]);
37
+ if (e.continueOnError) {
38
+ e.onError?.(t, [a]);
37
39
  return;
38
40
  }
39
- throw new R(e, [c]);
41
+ throw new V(t, [a]);
40
42
  }
41
- const r = E(i);
43
+ const r = Z(o);
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 V(t, r.errors);
48
50
  }
49
- const o = j(i);
50
- k.set(o.name, o);
51
+ const s = ee(o);
52
+ S.set(s.name, s);
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);
55
- if (!o.success) {
56
- if (t.continueOnError) {
57
- t.onError?.(n, o.errors);
54
+ function Ie(t, e = {}) {
55
+ for (const [n, o] of Object.entries(t)) {
56
+ const r = { ...o, name: n }, s = Z(r);
57
+ if (!s.success) {
58
+ if (e.continueOnError) {
59
+ e.onError?.(n, s.errors);
58
60
  continue;
59
61
  }
60
- throw new R(n, o.errors);
62
+ throw new V(n, s.errors);
61
63
  }
62
- const s = j(r);
63
- k.set(s.name, s);
64
+ const c = ee(r);
65
+ S.set(c.name, c);
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 j(t) {
69
+ const e = S.get(t);
70
+ if (e) return e;
71
+ for (const n of S.values())
72
+ if (n.slug === t) return n;
71
73
  }
72
- function K() {
73
- return Array.from(k.values());
74
+ function ge() {
75
+ return Array.from(S.values());
74
76
  }
75
- function Oe(e) {
76
- return k.has(e);
77
+ function Be(t) {
78
+ return S.has(t);
77
79
  }
78
- function Fe() {
79
- k.clear();
80
+ function Le() {
81
+ S.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 Pe() {
84
+ const t = [];
85
+ for (const e of S.values()) {
86
+ e.inherits && !S.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" && (S.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 H = /* @__PURE__ */ new Map();
99
+ function me(t, e) {
100
+ H.set(t, e);
99
101
  }
100
- function Z(e) {
101
- return w.get(e);
102
+ function he(t) {
103
+ return H.get(t);
102
104
  }
103
- function Ae(e) {
104
- return w.has(e);
105
+ function Te(t) {
106
+ return H.has(t);
105
107
  }
106
- function De() {
107
- w.clear();
108
+ function He() {
109
+ H.clear();
108
110
  }
109
- const ee = async (e, t) => {
110
- const [n] = e, { doctype: i } = t, r = [];
111
- for (const o of i.fields)
112
- o.required && (n[o.fieldname] === void 0 || n[o.fieldname] === null) && r.push(o.label ?? o.fieldname);
111
+ const Se = async (t, e) => {
112
+ const [n] = t, { doctype: o } = e, r = [];
113
+ for (const s of o.fields)
114
+ s.required && (n[s.fieldname] === void 0 || n[s.fieldname] === null) && r.push(s.label ?? s.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
- for (const o of i.fields) {
119
- const s = n[o.fieldname];
120
- if (s == null) continue;
121
- const c = ne(o, s);
122
- c && r.push(c);
118
+ }, $e = async (t, e) => {
119
+ const [n] = t, { doctype: o } = e, r = [];
120
+ for (const s of o.fields) {
121
+ const c = n[s.fieldname];
122
+ if (c == null) continue;
123
+ const a = we(s, c);
124
+ a && r.push(a);
123
125
  }
124
- if (i.links)
125
- for (const [o, s] of Object.entries(i.links)) {
126
- const c = n[o];
127
- 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}`);
126
+ if (o.links)
127
+ for (const [s, c] of Object.entries(o.links)) {
128
+ const a = n[s];
129
+ if (a == null) continue;
130
+ c.cardinality === "noneOrMany" || c.cardinality === "atLeastOne" ? Array.isArray(a) || r.push(`${s}: expected array, got ${typeof a}`) : (typeof a != "object" || Array.isArray(a)) && r.push(`${s}: expected object, got ${typeof a}`);
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
- switch (i) {
138
+ function we(t, e) {
139
+ const { fieldname: n, fieldtype: o } = t;
140
+ switch (o) {
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 ke = async () => ({ ok: !0 }), Ee = {
177
+ validateRequiredFields: Se,
178
+ validateFieldTypes: $e,
179
+ noop: ke
178
180
  };
179
- function ve() {
180
- for (const [e, t] of Object.entries(oe))
181
- X(e, t);
181
+ function Je() {
182
+ for (const [t, e] of Object.entries(Ee))
183
+ me(t, e);
182
184
  }
183
- const ie = V`
185
+ const Y = /* @__PURE__ */ new Map();
186
+ function We(t, e) {
187
+ Y.set(t, e);
188
+ }
189
+ function be(t) {
190
+ return Y.get(t);
191
+ }
192
+ function qe() {
193
+ Y.clear();
194
+ }
195
+ const Me = le`
184
196
  type StonecropFieldMeta {
185
197
  fieldname: String!
186
198
  fieldtype: String!
@@ -218,7 +230,6 @@ const ie = V`
218
230
  type StonecropDoctypeMeta {
219
231
  name: String!
220
232
  slug: String
221
- tableName: String
222
233
  fields: [StonecropFieldMeta!]!
223
234
  workflow: StonecropWorkflowMeta
224
235
  inherits: String
@@ -259,345 +270,294 @@ const ie = V`
259
270
  extend type Mutation {
260
271
  stonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!
261
272
  }
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
- );
273
+ `, _e = (t = {}) => {
274
+ const e = t.debug ? (n, o) => (console.log(`[@stonecrop/graphql-middleware] ${o.text}`, o.values ?? []), n.query(o)) : (n, o) => n.query(o);
275
+ return de((n) => {
276
+ const o = n.input?.pgRegistry?.pgExecutors, r = o ? Object.values(o)[0] : void 0;
277
+ if (!r)
278
+ throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
279
+ return {
280
+ typeDefs: Me,
281
+ objects: {
282
+ Query: {
283
+ plans: {
284
+ stonecropMeta(s, { $doctype: c }) {
285
+ return ae(c, (a) => j(a) ?? null);
286
+ },
287
+ stonecropAllMeta() {
288
+ return ce(ge());
289
+ },
290
+ stonecropRecord(s, { $doctype: c, $id: a, $options: $ }) {
291
+ return K(
292
+ r,
293
+ Q({ doctype: c, id: a, options: $ }),
294
+ async (E, y) => {
295
+ const g = /* @__PURE__ */ new Map();
296
+ for (let i = 0; i < y.length; i++) {
297
+ const l = y[i].doctype;
298
+ g.has(l) || g.set(l, []), g.get(l).push(i);
299
+ }
300
+ const m = new Array(y.length);
301
+ for (const [i, l] of g) {
302
+ const d = j(i);
303
+ if (!d) {
304
+ for (const p of l) m[p] = { data: null, doctype: i };
305
+ continue;
306
+ }
307
+ const D = X(d);
308
+ if (!D) {
309
+ for (const p of l) m[p] = { data: null, doctype: i };
310
+ continue;
311
+ }
312
+ const w = x(D.fieldname), C = U(d), J = l.map((p) => y[p].id), { rows: B } = await e(E, {
313
+ text: `SELECT ${C} FROM ${I(d.name, t.tables)} WHERE "${w}"::text = ANY($1::text[])`,
314
+ values: [J]
315
+ }), v = new Map(B.map((p) => [String(p[D.fieldname]), p]));
316
+ for (const p of l) {
317
+ const F = y[p].id, f = v.get(F);
318
+ if (!f) {
319
+ m[p] = { data: null, doctype: i };
320
+ continue;
321
+ }
322
+ const u = { ...f }, h = y[p].options ?? {}, R = h.includeNested === !0, b = Array.isArray(h.includeNested) ? new Set(h.includeNested) : null;
323
+ if (d.links)
324
+ for (const [M, k] of Object.entries(d.links)) {
325
+ const P = k.fetch, W = k.cardinality === "noneOrMany" || k.cardinality === "atLeastOne", q = P?.method ?? (W ? "sync" : "lazy"), z = P?.method === "sync" ? P.limit : W ? 50 : void 0;
326
+ if (!(R || (b ? b.has(M) : q === "sync"))) continue;
327
+ if (q === "custom") {
328
+ const A = P.handler, O = be(A);
329
+ O && (u[M] = await O(E, u, k));
330
+ continue;
331
+ }
332
+ if (q !== "sync" && !b?.has(M)) continue;
333
+ const N = j(k.target);
334
+ if (!N) continue;
335
+ const G = U(N);
336
+ if (W) {
337
+ if (!k.backlink) continue;
338
+ const A = x(k.backlink);
339
+ let O = `SELECT ${G} FROM ${I(N.name, t.tables)} WHERE "${A}"::text = $1`;
340
+ const T = [F];
341
+ z != null && (O += " LIMIT $2", T.push(z));
342
+ const { rows: _ } = await e(E, {
343
+ text: O,
344
+ values: T
345
+ });
346
+ u[M] = _;
347
+ } else {
348
+ if (!k.fieldname) continue;
349
+ const A = u[k.fieldname];
350
+ if (A == null) {
351
+ u[M] = null;
352
+ continue;
353
+ }
354
+ const O = X(N);
355
+ if (!O) continue;
356
+ const T = x(O.fieldname), { rows: _ } = await e(E, {
357
+ text: `SELECT ${G} FROM ${I(N.name, t.tables)} WHERE "${T}" = $1`,
358
+ values: [A]
359
+ });
360
+ u[M] = _[0] ?? null;
361
+ }
362
+ }
363
+ const L = b && d.links ? [...b].filter((M) => !(M in d.links)) : void 0;
364
+ m[p] = {
365
+ data: u,
366
+ doctype: i,
367
+ unknownLinks: L?.length ? L : void 0
368
+ };
369
+ }
370
+ }
371
+ return m;
372
+ }
373
+ );
374
+ },
375
+ stonecropRecords(s, { $doctype: c, $filters: a, $orderBy: $, $limit: E, $offset: y }) {
376
+ return K(
377
+ r,
378
+ Q({
379
+ doctype: c,
380
+ filters: a,
381
+ orderBy: $,
382
+ limit: E,
383
+ offset: y
384
+ }),
385
+ async (g, m) => await Promise.all(
386
+ m.map(async (i) => {
387
+ const l = j(i.doctype);
388
+ if (!l)
389
+ return { data: [], doctype: i.doctype, count: 0 };
390
+ const d = new Set(l.fields.map((f) => f.fieldname)), D = U(l), w = [], C = [];
391
+ if (i.filters != null)
392
+ for (const [f, u] of Object.entries(i.filters)) {
393
+ if (!d.has(f))
394
+ throw new Error(`Unknown filter field: ${f} for doctype ${l.name}`);
395
+ w.push(u), C.push(`"${x(f)}" = $${w.length}`);
396
+ }
397
+ const J = C.length > 0 ? ` WHERE ${C.join(" AND ")}` : "";
398
+ let B = "";
399
+ if (i.orderBy != null) {
400
+ const f = i.orderBy, u = f.lastIndexOf("_");
401
+ if (u <= 0)
402
+ throw new Error(`Invalid orderBy format: "${f}". Expected FIELD_ASC or FIELD_DESC`);
403
+ const h = f.slice(u + 1).toUpperCase();
404
+ if (h !== "ASC" && h !== "DESC")
405
+ throw new Error(`Invalid orderBy direction: "${h}". Must be ASC or DESC`);
406
+ const R = f.slice(0, u);
407
+ if (!d.has(R))
408
+ throw new Error(`Unknown orderBy field: "${R}" for doctype ${l.name}`);
409
+ B = ` ORDER BY "${x(R)}" ${h}`;
410
+ }
411
+ let v = "";
412
+ i.limit != null && (w.push(i.limit), v += ` LIMIT $${w.length}`), i.offset != null && (w.push(i.offset), v += ` OFFSET $${w.length}`);
413
+ const { rows: p } = await e(g, {
414
+ text: `SELECT ${D} FROM ${I(l.name, t.tables)}${J}${B}${v}`,
415
+ values: w
416
+ });
417
+ let F = p.length;
418
+ if (i.limit != null || i.offset != null) {
419
+ const f = [], u = [];
420
+ if (i.filters != null)
421
+ for (const [b, L] of Object.entries(i.filters))
422
+ d.has(b) && (f.push(L), u.push(`"${x(b)}" = $${f.length}`));
423
+ const h = u.length > 0 ? ` WHERE ${u.join(" AND ")}` : "", { rows: R } = await e(g, {
424
+ text: `SELECT COUNT(*) AS __count FROM ${I(l.name, t.tables)}${h}`,
425
+ values: f
426
+ });
427
+ F = parseInt(R[0]?.__count ?? "0", 10);
428
+ }
429
+ return { data: p, doctype: i.doctype, count: F };
430
+ })
431
+ )
432
+ );
433
+ }
355
434
  }
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)
435
+ },
436
+ Mutation: {
437
+ plans: {
438
+ stonecropAction(s, { $doctype: c, $action: a, $args: $ }) {
439
+ return se(
440
+ r,
441
+ Q({ doctype: c, action: a, actionArgs: $ }),
442
+ async (E, y) => {
443
+ const g = j(y.doctype);
444
+ if (!g)
371
445
  return {
372
446
  success: !1,
373
447
  data: null,
374
- error: `Unknown doctype: ${d.doctype}`
448
+ error: `Unknown doctype: ${y.doctype}`
375
449
  };
376
- const y = f.workflow?.actions?.[d.action];
377
- if (!y)
450
+ const m = g.workflow?.actions?.[y.action];
451
+ if (!m)
378
452
  return {
379
453
  success: !1,
380
454
  data: null,
381
- error: `Unknown action: ${d.action} on ${d.doctype}`
455
+ error: `Unknown action: ${y.action} on ${y.doctype}`
382
456
  };
383
- const m = y.handler, g = Z(m);
384
- if (!g)
457
+ const i = he(m.handler);
458
+ if (!i)
385
459
  return {
386
460
  success: !1,
387
461
  data: null,
388
- error: `Handler not registered: ${m}`
462
+ error: `Handler not registered: ${m.handler}`
389
463
  };
390
- const h = {
391
- doctype: f,
392
- executor: e.executor
393
- };
464
+ const l = { doctype: g, pgClient: E };
394
465
  try {
395
- return {
396
- success: !0,
397
- data: await g(d.actionArgs ?? [], h),
398
- error: null
399
- };
400
- } catch (S) {
466
+ return { success: !0, data: await i(y.actionArgs ?? [], l), error: null };
467
+ } catch (d) {
401
468
  return {
402
469
  success: !1,
403
470
  data: null,
404
- error: S instanceof Error ? S.message : String(S)
471
+ error: d instanceof Error ? d.message : String(d)
405
472
  };
406
473
  }
407
- })
408
- )
409
- );
474
+ }
475
+ );
476
+ }
410
477
  }
411
478
  }
412
479
  }
413
- }
414
- }));
480
+ };
481
+ });
415
482
  };
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";
428
- }
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);
485
- }
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
- }`);
483
+ function U(t) {
484
+ const e = /* @__PURE__ */ new Set();
485
+ if (t.links)
486
+ for (const [o, r] of Object.entries(t.links))
487
+ e.add(r.fieldname ?? o);
488
+ const n = [];
489
+ for (const o of t.fields) {
490
+ if (o.fieldtype === "Display" || o.fieldtype === "Link" && e.has(o.fieldname)) continue;
491
+ const r = x(o.fieldname);
492
+ n.push(r !== o.fieldname ? `"${r}" AS "${o.fieldname}"` : `"${o.fieldname}"`);
505
493
  }
506
- return p.join("");
494
+ return n.join(", ");
507
495
  }
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
- `;
496
+ function X(t) {
497
+ return t.fields.find((e) => e.fieldtype === "PrimaryKey");
532
498
  }
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
- `;
499
+ function I(t, e) {
500
+ const n = e?.[t] ?? ie(t), o = n.indexOf(".");
501
+ return o > 0 ? `"${n.slice(0, o)}"."${n.slice(o + 1)}"` : `"${n}"`;
546
502
  }
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]);
503
+ const Qe = (t = {}) => {
504
+ const { logPlans: e = !0, logTiming: n = !1 } = t, o = (r, s) => ({
505
+ plan: (c) => {
506
+ e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${r}.${s}`);
507
+ const a = n ? Date.now() : 0, $ = c();
508
+ return n && console.log(
509
+ `[@stonecrop/graphql-middleware] Plan built for ${r}.${s} in ${Date.now() - a}ms`
510
+ ), $;
561
511
  }
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
- }
512
+ });
513
+ return fe({
514
+ Query: {
515
+ stonecropRecord: o("Query", "stonecropRecord"),
516
+ stonecropRecords: o("Query", "stonecropRecords"),
517
+ stonecropMeta: o("Query", "stonecropMeta"),
518
+ stonecropAllMeta: o("Query", "stonecropAllMeta")
519
+ },
520
+ Mutation: {
521
+ stonecropAction: o("Mutation", "stonecropAction")
522
+ }
523
+ });
524
+ }, Oe = {
525
+ name: "StonecropFieldCasingPlugin",
526
+ version: "0.0.0",
527
+ inflection: {
528
+ replace: {
529
+ attribute(t, e, n) {
530
+ return this.upperCamelCase(this._attributeName(n));
531
+ }
532
+ }
533
+ }
534
+ }, Re = (t) => ({
535
+ extends: [ue],
536
+ plugins: t?.fieldCasing === "pascal" ? [Oe] : []
537
+ }), Ue = Re();
572
538
  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,
579
- 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
539
+ V as DoctypeValidationError,
540
+ Ue as StonecropPreset,
541
+ Ee as builtinHandlers,
542
+ qe as clearFetchHandlers,
543
+ He as clearHandlers,
544
+ Le as clearRegistry,
545
+ Qe as createDebugPlugin,
546
+ _e as createStonecropPlugin,
547
+ Re as createStonecropPreset,
548
+ ge as getAllMeta,
549
+ be as getFetchHandler,
550
+ he as getHandler,
551
+ j as getMeta,
552
+ Te as hasHandler,
553
+ Be as hasMeta,
554
+ pe as loadDoctypes,
555
+ Ie as loadDoctypesFromObject,
556
+ ze as makePgService,
557
+ Je as registerBuiltinHandlers,
558
+ We as registerFetchHandler,
559
+ me as registerHandler,
560
+ Me as typeDefs,
561
+ Pe as validateReferences
602
562
  };
603
563
  //# sourceMappingURL=index.js.map