@stonecrop/graphql-middleware 0.16.4 → 0.16.5
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 +71 -71
- package/dist/index.js.map +1 -1
- package/dist/src/plugin/postgraphile.js +5 -2
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { readdirSync as et, statSync as nt, readFileSync as ot } from "node:fs";
|
|
2
2
|
import { join as rt } from "node:path";
|
|
3
|
-
import { validateDoctype as Z, parseDoctype as tt, isActionAllowedInState as st, camelToSnake as A,
|
|
4
|
-
import { sideEffectWithPgClient as
|
|
5
|
-
import { object as q, constant as
|
|
6
|
-
import { gql as
|
|
7
|
-
import { PostGraphileAmberPreset as
|
|
8
|
-
import { makePgService as
|
|
3
|
+
import { validateDoctype as Z, parseDoctype as tt, isActionAllowedInState as st, camelToSnake as A, getPrimaryKeyField as it, pascalToSnake as at, resolveLinkRenderMode as ct } from "@stonecrop/schema";
|
|
4
|
+
import { sideEffectWithPgClient as lt, loadOneWithPgClient as X } from "@dataplan/pg";
|
|
5
|
+
import { object as q, constant as ut, lambda as dt } from "postgraphile/grafast";
|
|
6
|
+
import { gql as ft, extendSchema as pt, wrapPlans as gt } from "postgraphile/utils";
|
|
7
|
+
import { PostGraphileAmberPreset as yt } from "postgraphile/presets/amber";
|
|
8
|
+
import { makePgService as qt } from "postgraphile/adaptors/pg";
|
|
9
9
|
const w = /* @__PURE__ */ new Map();
|
|
10
10
|
class V extends Error {
|
|
11
11
|
constructor(e, o) {
|
|
@@ -17,14 +17,14 @@ ${n}`), this.file = e, this.errors = o, this.name = "DoctypeValidationError";
|
|
|
17
17
|
file;
|
|
18
18
|
errors;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function St(t, e = {}) {
|
|
21
21
|
const o = et(t);
|
|
22
22
|
for (const n of o) {
|
|
23
23
|
const s = rt(t, n);
|
|
24
|
-
nt(s).isDirectory() ?
|
|
24
|
+
nt(s).isDirectory() ? St(s, e) : n.endsWith(".json") && mt(s, e);
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
-
function
|
|
27
|
+
function mt(t, e) {
|
|
28
28
|
const o = ot(t, "utf-8");
|
|
29
29
|
let n;
|
|
30
30
|
try {
|
|
@@ -51,7 +51,7 @@ function St(t, e) {
|
|
|
51
51
|
const l = tt(n);
|
|
52
52
|
w.set(l.name, l);
|
|
53
53
|
}
|
|
54
|
-
function
|
|
54
|
+
function Nt(t, e = {}) {
|
|
55
55
|
for (const [o, n] of Object.entries(t)) {
|
|
56
56
|
const s = { ...typeof n == "object" && n !== null ? n : {}, name: o }, l = Z(s);
|
|
57
57
|
if (!l.success) {
|
|
@@ -71,16 +71,16 @@ function T(t) {
|
|
|
71
71
|
for (const o of w.values())
|
|
72
72
|
if (o.slug === t) return o;
|
|
73
73
|
}
|
|
74
|
-
function
|
|
74
|
+
function wt() {
|
|
75
75
|
return Array.from(w.values());
|
|
76
76
|
}
|
|
77
|
-
function
|
|
77
|
+
function It(t) {
|
|
78
78
|
return w.has(t);
|
|
79
79
|
}
|
|
80
|
-
function
|
|
80
|
+
function Dt() {
|
|
81
81
|
w.clear();
|
|
82
82
|
}
|
|
83
|
-
function
|
|
83
|
+
function Lt() {
|
|
84
84
|
const t = [];
|
|
85
85
|
for (const e of w.values()) {
|
|
86
86
|
e.inherits && !w.has(e.inherits) && t.push({
|
|
@@ -105,16 +105,16 @@ function Dt() {
|
|
|
105
105
|
return t;
|
|
106
106
|
}
|
|
107
107
|
const G = /* @__PURE__ */ new Map();
|
|
108
|
-
function
|
|
108
|
+
function Tt(t, e) {
|
|
109
109
|
G.set(t, e);
|
|
110
110
|
}
|
|
111
|
-
function
|
|
111
|
+
function ht(t) {
|
|
112
112
|
return G.get(t);
|
|
113
113
|
}
|
|
114
|
-
function
|
|
114
|
+
function Pt() {
|
|
115
115
|
G.clear();
|
|
116
116
|
}
|
|
117
|
-
async function
|
|
117
|
+
async function $t(t, e, o) {
|
|
118
118
|
if (!t.selfTransition && t.nextState == null)
|
|
119
119
|
return {
|
|
120
120
|
success: !1,
|
|
@@ -136,7 +136,7 @@ async function ht(t, e, o) {
|
|
|
136
136
|
error: `Action not allowed from state: ${n || "(unknown)"}`
|
|
137
137
|
};
|
|
138
138
|
}
|
|
139
|
-
const
|
|
139
|
+
const kt = ft`
|
|
140
140
|
type StonecropFieldMeta {
|
|
141
141
|
kind: String!
|
|
142
142
|
fieldname: String!
|
|
@@ -222,20 +222,20 @@ const $t = dt`
|
|
|
222
222
|
}
|
|
223
223
|
`, jt = (t = {}) => {
|
|
224
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
|
|
225
|
+
return pt((o) => {
|
|
226
226
|
const n = o.input?.pgRegistry?.pgExecutors, s = n ? Object.values(n)[0] : void 0;
|
|
227
227
|
if (!s)
|
|
228
228
|
throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
|
|
229
229
|
return {
|
|
230
|
-
typeDefs:
|
|
230
|
+
typeDefs: kt,
|
|
231
231
|
objects: {
|
|
232
232
|
Query: {
|
|
233
233
|
plans: {
|
|
234
234
|
stonecropMeta(l, { $doctype: f }) {
|
|
235
|
-
return
|
|
235
|
+
return dt(f, (y) => T(String(y)) ?? null);
|
|
236
236
|
},
|
|
237
237
|
stonecropAllMeta() {
|
|
238
|
-
return
|
|
238
|
+
return ut(wt());
|
|
239
239
|
},
|
|
240
240
|
stonecropRecord(l, { $doctype: f, $id: y, $options: M }) {
|
|
241
241
|
return X(
|
|
@@ -259,12 +259,12 @@ const $t = dt`
|
|
|
259
259
|
for (const d of p) h[d] = { data: null, doctype: r };
|
|
260
260
|
continue;
|
|
261
261
|
}
|
|
262
|
-
const b = A(R.fieldname), c = U(a),
|
|
262
|
+
const b = A(R.fieldname), c = U(a), F = p.map((d) => String(u[d].id)), { rows: W } = await e(k, {
|
|
263
263
|
text: `SELECT ${c} FROM ${C(a.name, t.tables)} WHERE "${b}"::text = ANY($1::text[])`,
|
|
264
|
-
values: [
|
|
265
|
-
}),
|
|
264
|
+
values: [F]
|
|
265
|
+
}), P = new Map(W.map((d) => [String(d[R.fieldname]), d]));
|
|
266
266
|
for (const d of p) {
|
|
267
|
-
const
|
|
267
|
+
const B = String(u[d].id), N = P.get(B);
|
|
268
268
|
if (!N) {
|
|
269
269
|
h[d] = { data: null, doctype: r };
|
|
270
270
|
continue;
|
|
@@ -275,7 +275,7 @@ const $t = dt`
|
|
|
275
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
276
|
if (!(v || (m ? m.has($) : H === "sync"))) continue;
|
|
277
277
|
if (H === "custom" && D?.method === "custom") {
|
|
278
|
-
const x = D.handler, O =
|
|
278
|
+
const x = D.handler, O = ht(x);
|
|
279
279
|
O && (i[$] = await O(k, i, E));
|
|
280
280
|
continue;
|
|
281
281
|
}
|
|
@@ -287,11 +287,11 @@ const $t = dt`
|
|
|
287
287
|
if (!E.backlink) continue;
|
|
288
288
|
const x = A(E.backlink);
|
|
289
289
|
let O = `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${x}"::text = $1`;
|
|
290
|
-
const
|
|
291
|
-
Y != null && (O += " LIMIT $2",
|
|
290
|
+
const j = [B];
|
|
291
|
+
Y != null && (O += " LIMIT $2", j.push(Y));
|
|
292
292
|
const { rows: _ } = await e(k, {
|
|
293
293
|
text: O,
|
|
294
|
-
values:
|
|
294
|
+
values: j
|
|
295
295
|
});
|
|
296
296
|
i[$] = _;
|
|
297
297
|
} else {
|
|
@@ -303,8 +303,8 @@ const $t = dt`
|
|
|
303
303
|
}
|
|
304
304
|
const O = Q(L);
|
|
305
305
|
if (!O) continue;
|
|
306
|
-
const
|
|
307
|
-
text: `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${
|
|
306
|
+
const j = A(O.fieldname), { rows: _ } = await e(k, {
|
|
307
|
+
text: `SELECT ${z} FROM ${C(L.name, t.tables)} WHERE "${j}" = $1`,
|
|
308
308
|
values: [x]
|
|
309
309
|
});
|
|
310
310
|
i[$] = _[0] ?? null;
|
|
@@ -337,15 +337,15 @@ const $t = dt`
|
|
|
337
337
|
const p = String(r.doctype), a = T(p);
|
|
338
338
|
if (!a)
|
|
339
339
|
return { data: [], doctype: p, count: 0 };
|
|
340
|
-
const R = new Set(K(a.fields).map((i) => i.fieldname)), b = U(a), c = [],
|
|
340
|
+
const R = new Set(K(a.fields).map((i) => i.fieldname)), b = U(a), c = [], F = [];
|
|
341
341
|
if (r.filters != null)
|
|
342
342
|
for (const [i, g] of Object.entries(r.filters)) {
|
|
343
343
|
if (!R.has(i))
|
|
344
344
|
throw new Error(`Unknown filter field: ${i} for doctype ${a.name}`);
|
|
345
|
-
c.push(g),
|
|
345
|
+
c.push(g), F.push(`"${A(i)}" = $${c.length}`);
|
|
346
346
|
}
|
|
347
|
-
const W =
|
|
348
|
-
let
|
|
347
|
+
const W = F.length > 0 ? ` WHERE ${F.join(" AND ")}` : "";
|
|
348
|
+
let P = "";
|
|
349
349
|
if (r.orderBy != null) {
|
|
350
350
|
if (typeof r.orderBy != "string")
|
|
351
351
|
throw new Error(`Invalid orderBy: expected string, got ${typeof r.orderBy}`);
|
|
@@ -358,15 +358,15 @@ const $t = dt`
|
|
|
358
358
|
const m = i.slice(0, g);
|
|
359
359
|
if (!R.has(m))
|
|
360
360
|
throw new Error(`Unknown orderBy field: "${m}" for doctype ${a.name}`);
|
|
361
|
-
|
|
361
|
+
P = ` ORDER BY "${A(m)}" ${v}`;
|
|
362
362
|
}
|
|
363
363
|
let d = "";
|
|
364
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:
|
|
366
|
-
text: `SELECT ${b} FROM ${C(a.name, t.tables)}${W}${
|
|
365
|
+
const { rows: B } = await e(S, {
|
|
366
|
+
text: `SELECT ${b} FROM ${C(a.name, t.tables)}${W}${P}${d}`,
|
|
367
367
|
values: c
|
|
368
368
|
});
|
|
369
|
-
let N =
|
|
369
|
+
let N = B.length;
|
|
370
370
|
if (r.limit != null || r.offset != null) {
|
|
371
371
|
const i = [], g = [];
|
|
372
372
|
if (r.filters != null)
|
|
@@ -378,7 +378,7 @@ const $t = dt`
|
|
|
378
378
|
});
|
|
379
379
|
N = parseInt(m[0]?.row_count ?? "0", 10);
|
|
380
380
|
}
|
|
381
|
-
return { data:
|
|
381
|
+
return { data: B, doctype: p, count: N };
|
|
382
382
|
})
|
|
383
383
|
)
|
|
384
384
|
);
|
|
@@ -388,7 +388,7 @@ const $t = dt`
|
|
|
388
388
|
Mutation: {
|
|
389
389
|
plans: {
|
|
390
390
|
stonecropAction(l, { $doctype: f, $action: y, $args: M }) {
|
|
391
|
-
return
|
|
391
|
+
return lt(
|
|
392
392
|
s,
|
|
393
393
|
q({ doctype: f, action: y, actionArgs: M }),
|
|
394
394
|
async (k, u) => {
|
|
@@ -415,7 +415,7 @@ const $t = dt`
|
|
|
415
415
|
};
|
|
416
416
|
const p = A(r.fieldname), a = C(S.name, t.tables), b = (Array.isArray(u.actionArgs) ? u.actionArgs : [])[0]?.id;
|
|
417
417
|
try {
|
|
418
|
-
return await
|
|
418
|
+
return await $t(h, {
|
|
419
419
|
readState: async () => {
|
|
420
420
|
if (b == null) return;
|
|
421
421
|
const { rows: c } = await e(k, {
|
|
@@ -453,12 +453,12 @@ function K(t) {
|
|
|
453
453
|
o.kind === "fieldset" ? e.push(...K(o.schema)) : e.push(o);
|
|
454
454
|
return e;
|
|
455
455
|
}
|
|
456
|
-
function
|
|
456
|
+
function Et(t, e) {
|
|
457
457
|
const o = [];
|
|
458
458
|
for (const n of K(t)) {
|
|
459
459
|
if (n.kind !== "field" || n.computed) continue;
|
|
460
460
|
const s = e.get(n.fieldname);
|
|
461
|
-
if (s &&
|
|
461
|
+
if (s && ct(s, n.component) !== "inline") continue;
|
|
462
462
|
const l = A(n.fieldname);
|
|
463
463
|
o.push(l !== n.fieldname ? `"${l}" AS "${n.fieldname}"` : `"${n.fieldname}"`);
|
|
464
464
|
}
|
|
@@ -469,16 +469,16 @@ function U(t) {
|
|
|
469
469
|
if (t.links)
|
|
470
470
|
for (const [o, n] of Object.entries(t.links))
|
|
471
471
|
e.set(n.fieldname ?? o, n);
|
|
472
|
-
return
|
|
472
|
+
return Et(t.fields, e).join(", ");
|
|
473
473
|
}
|
|
474
474
|
function Q(t) {
|
|
475
|
-
return t.fields
|
|
475
|
+
return it(t.fields);
|
|
476
476
|
}
|
|
477
477
|
function C(t, e) {
|
|
478
|
-
const o = e?.[t] ??
|
|
478
|
+
const o = e?.[t] ?? at(t), n = o.indexOf(".");
|
|
479
479
|
return n > 0 ? `"${o.slice(0, n)}"."${o.slice(n + 1)}"` : `"${o}"`;
|
|
480
480
|
}
|
|
481
|
-
const
|
|
481
|
+
const Wt = (t = {}) => {
|
|
482
482
|
const { logPlans: e = !0, logTiming: o = !1 } = t, n = (s, l) => ({
|
|
483
483
|
plan: (f) => {
|
|
484
484
|
e && console.log(`[@stonecrop/graphql-middleware] Building plan for ${s}.${l}`);
|
|
@@ -488,7 +488,7 @@ const Pt = (t = {}) => {
|
|
|
488
488
|
), M;
|
|
489
489
|
}
|
|
490
490
|
});
|
|
491
|
-
return
|
|
491
|
+
return gt({
|
|
492
492
|
Query: {
|
|
493
493
|
stonecropRecord: n("Query", "stonecropRecord"),
|
|
494
494
|
stonecropRecords: n("Query", "stonecropRecords"),
|
|
@@ -499,7 +499,7 @@ const Pt = (t = {}) => {
|
|
|
499
499
|
stonecropAction: n("Mutation", "stonecropAction")
|
|
500
500
|
}
|
|
501
501
|
});
|
|
502
|
-
},
|
|
502
|
+
}, Mt = {
|
|
503
503
|
name: "StonecropFieldCasingPlugin",
|
|
504
504
|
version: "0.0.0",
|
|
505
505
|
inflection: {
|
|
@@ -509,28 +509,28 @@ const Pt = (t = {}) => {
|
|
|
509
509
|
}
|
|
510
510
|
}
|
|
511
511
|
}
|
|
512
|
-
},
|
|
513
|
-
extends: [
|
|
514
|
-
plugins: t?.fieldCasing === "pascal" ? [
|
|
515
|
-
}),
|
|
512
|
+
}, Rt = (t) => ({
|
|
513
|
+
extends: [yt],
|
|
514
|
+
plugins: t?.fieldCasing === "pascal" ? [Mt] : []
|
|
515
|
+
}), Jt = Rt();
|
|
516
516
|
export {
|
|
517
517
|
V as DoctypeValidationError,
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
518
|
+
Jt as StonecropPreset,
|
|
519
|
+
$t as applyGuardedTransition,
|
|
520
|
+
Pt as clearFetchHandlers,
|
|
521
|
+
Dt as clearRegistry,
|
|
522
|
+
Wt as createDebugPlugin,
|
|
523
523
|
jt as createStonecropPlugin,
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
524
|
+
Rt as createStonecropPreset,
|
|
525
|
+
wt as getAllMeta,
|
|
526
|
+
ht as getFetchHandler,
|
|
527
527
|
T as getMeta,
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
528
|
+
It as hasMeta,
|
|
529
|
+
St as loadDoctypes,
|
|
530
|
+
Nt as loadDoctypesFromObject,
|
|
531
|
+
qt as makePgService,
|
|
532
|
+
Tt as registerFetchHandler,
|
|
533
|
+
kt as typeDefs,
|
|
534
|
+
Lt as validateReferences
|
|
535
535
|
};
|
|
536
536
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(typeof data === 'object' && data !== null ? data : {}), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\tconst direct = doctypeRegistry.get(name)\n\tif (direct) return direct\n\t// Fallback: find by slug (links reference doctypes by slug, not name)\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\tif (doctype.slug === name) return doctype\n\t}\n\treturn undefined\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && !doctypeRegistry.has(target)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'doctype'],\n\t\t\t\t\tmessage: `Link references unknown doctype: ${target}`,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Check link-declaration targets (component-primary links live in the `links` map)\n\t\tif (doctype.links) {\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (!doctypeRegistry.has(link.target)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'target'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${link.target}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { PgClient } from '@dataplan/pg'\nimport type { LinkDeclaration } from '@stonecrop/schema'\n\n/**\n * Handler for a custom fetch strategy on a link declaration.\n * Called during `stonecropRecord` resolution when `link.fetch.method === 'custom'`.\n *\n * @param pgClient - Active database client for the current request\n * @param parentRecord - Resolved parent record (scalar fields already populated)\n * @param link - The link declaration, giving access to cardinality and other metadata\n * @returns A single linked record or an array depending on `link.cardinality`\n * @public\n */\nexport type FetchHandler = (\n\tpgClient: PgClient,\n\tparentRecord: Record<string, unknown>,\n\tlink: LinkDeclaration\n) => Promise<Record<string, unknown> | Record<string, unknown>[]>\n\nconst registry = new Map<string, FetchHandler>()\n\n/**\n * Register a custom fetch handler by name.\n * The name must match the `handler` field on a `CustomFetch` strategy declaration.\n * @public\n */\nexport function registerFetchHandler(name: string, handler: FetchHandler): void {\n\tregistry.set(name, handler)\n}\n\n/**\n * Retrieve a registered fetch handler by name.\n * Returns `undefined` if no handler has been registered under that name.\n * @public\n */\nexport function getFetchHandler(name: string): FetchHandler | undefined {\n\treturn registry.get(name)\n}\n\n/**\n * Remove all registered fetch handlers. Primarily for test isolation.\n * @public\n */\nexport function clearFetchHandlers(): void {\n\tregistry.clear()\n}\n","import { isActionAllowedInState } from '@stonecrop/schema'\n\n/**\n * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.\n * The same guard runs whether the record lives in Postgres, a mock executor, or an\n * in-memory Map — only these two closures change per backend.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/** Read the record's current workflow state (the value of its `status` field), or undefined if unknown. */\n\treadState: () => Promise<string | undefined>\n\t/** Persist the record's new workflow state, written verbatim. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Persist record field data for a mutate-in-place self-transition, returning the full updated\n\t * record (so the client writeback reflects the new data). Optional: a backend with no data-write\n\t * path (e.g. PostGraphile today, which writes only `status`) omits it, and a self-transition is\n\t * then rejected loudly rather than silently dropped.\n\t */\n\twriteData?: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>\n}\n\n/**\n * Apply a workflow action's state transition on the server, enforcing `allowedStates`.\n *\n * The server owns the transition: it reads the record's authoritative current state,\n * rejects the action when `isActionAllowedInState` denies it, then writes `nextState`\n * verbatim. Storage access is injected via `io` so this one guard serves every backend\n * and can never disagree with the frontend's `getAvailableTransitions`, which shares the\n * same predicate.\n *\n * There are three action shapes this guard distinguishes:\n * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\n * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current\n * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.\n * A backend without a data-write path rejects it loudly instead of dropping it silently.\n * - Anything else with no `nextState` and no `selfTransition` flag is a genuine authoring mistake (or a\n * stateless side-effect command whose server handler is not wired — the intended `callHandler` primitive\n * is still unimplemented): it fails loudly before touching the backend rather than reporting a false success.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`\n * @param io - Backend read/write closures\n * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)\n * @returns Action result envelope — the resulting `data.state` for a transition, the full record for a self-transition\n * @public\n */\nexport async function applyGuardedTransition(\n\tactionDef: { label?: string; allowedStates?: string[]; nextState?: string; selfTransition?: boolean },\n\tio: GuardedTransitionIO,\n\tdata?: Record<string, unknown>\n): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\t// A non-self action with no target has nothing to apply — fail loudly WITHOUT touching the backend\n\t// (a stateless command's server handler is not wired; a genuine bug should not read/write anything).\n\tif (!actionDef.selfTransition && actionDef.nextState == null) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" has no workflow transition and no server-side effect is wired — nothing was executed.`,\n\t\t}\n\t}\n\n\tconst currentState = (await io.readState()) ?? ''\n\n\tif (!isActionAllowedInState(actionDef, currentState)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action not allowed from state: ${currentState || '(unknown)'}`,\n\t\t}\n\t}\n\n\t// Self-transition: mutate record data in place, keep the current state. Requires a backend data-write\n\t// capability; without it (e.g. PostGraphile today) reject loudly. The full updated record is returned\n\t// so the client writeback reflects the new data.\n\tif (actionDef.selfTransition) {\n\t\tif (!io.writeData) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" persists record data in place, which this backend does not support.`,\n\t\t\t}\n\t\t}\n\t\tconst record = await io.writeData(data ?? {})\n\t\treturn { success: true, data: record, error: null }\n\t}\n\n\t// NON-ATOMIC: the current state is read above and nextState written here as two\n\t// separate statements. Two concurrent transitions on the same record can both pass\n\t// the guard before either writes, so both \"succeed\" even when the workflow intended\n\t// them to be mutually exclusive. Closing this requires guarding and writing in one\n\t// statement — an atomic `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)`\n\t// — and reporting \"no rows updated\" as a rejected transition. Deferred for now.\n\tif (actionDef.nextState == null) {\n\t\t// Unreachable (guarded above), but keeps `nextState` narrowed to a string below.\n\t\treturn { success: false, data: null, error: 'nothing was executed' }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\treturn {\n\t\tsuccess: true,\n\t\tdata: { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { gql } from 'postgraphile/utils'\n\n/**\n * GraphQL type definitions for Stonecrop's middleware API.\n * Includes stonecropMeta, stonecropRecord, stonecropRecords, stonecropAction, and related types.\n * @public\n */\nexport const typeDefs = gql`\n\ttype StonecropFieldMeta {\n\t\tkind: String!\n\t\tfieldname: String!\n\t\tcomponent: String\n\t\tprimaryKey: Boolean\n\t\tcomputed: Boolean\n\t\tlanguage: String\n\t\tdoctype: String\n\t\tlabel: String\n\t\twidth: String\n\t\talign: String\n\t\tedit: Boolean\n\t\tmask: String\n\t\tformat: String\n\t\tmode: String\n\t\toptions: JSON\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\tvalidation: JSON\n\t\tcardinality: String\n\t\tsource: String\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tnextState: String\n\t\tstateless: Boolean\n\t\tselfTransition: Boolean\n\t\tclientHandler: String\n\t}\n\n\ttype StonecropWorkflowMeta {\n\t\tstates: [String!]\n\t\tactions: [StonecropWorkflowAction!]\n\t}\n\n\ttype StonecropDoctypeMeta {\n\t\tname: String!\n\t\tslug: String\n\t\tfields: [StonecropFieldMeta!]!\n\t\tworkflow: StonecropWorkflowMeta\n\t\tinherits: String\n\t}\n\n\ttype StonecropRecordResult {\n\t\tdata: JSON\n\t\tdoctype: String!\n\t\tunknownLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\tcount: Int!\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\tdata: JSON\n\t\terror: String\n\t}\n\n\textend type Query {\n\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\tstonecropRecord(doctype: String!, id: String!, options: JSON): StonecropRecordResult\n\t\tstonecropRecords(\n\t\t\tdoctype: String!\n\t\t\tfilters: JSON\n\t\t\torderBy: String\n\t\t\tlimit: Int\n\t\t\toffset: Int\n\t\t\toptions: JSON\n\t\t): StonecropRecordsResult\n\t}\n\n\textend type Mutation {\n\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t}\n`\n","import type {\n\tDoctypeField,\n\tDoctypeMeta,\n\tLinkDeclaration,\n\tTableField,\n\tValueField,\n\tGetRecordOptions,\n} from '@stonecrop/schema'\nimport { camelToSnake, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin.\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/**\n\t * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks\n\t * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.\n\t */\n\tdebug?: boolean\n\t/**\n\t * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.\n\t * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).\n\t * SQL fragments and subqueries are not supported.\n\t * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.\n\t */\n\ttables?: Record<string, string>\n}\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.\n *\n * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`\n * during schema construction — it does not need to be supplied by the caller.\n *\n * @param options - Optional plugin configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions = {}): GraphileConfig.Plugin => {\n\t/**\n\t * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging\n\t * for queries that run inside custom loadOneWithPgClient callbacks, which\n\t * bypass the executor's native instrumentation.\n\t */\n\tconst debugSql = options.debug\n\t\t? <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? [])\n\t\t\t\treturn pgClient.query<T>(query)\n\t\t\t}\n\t\t: <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => pgClient.query<T>(query)\n\n\treturn extendSchema(build => {\n\t\t// Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type\n\t\tconst pgExecutors = (build as any).input?.pgRegistry?.pgExecutors as Record<string, PgExecutor> | undefined\n\t\tconst executor = pgExecutors ? Object.values(pgExecutors)[0] : undefined\n\t\tif (!executor) {\n\t\t\tthrow new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured')\n\t\t}\n\n\t\treturn {\n\t\t\ttypeDefs,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(String(doctype))\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id, $options }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, id: $id, options: $options }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\t\t\t\t\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\t\t\t\t\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\t\t\t\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\t\t\t\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\t\t\t\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst results: Array<{\n\t\t\t\t\t\t\t\t\t\tdata: Record<string, unknown> | null\n\t\t\t\t\t\t\t\t\t\tdoctype: string\n\t\t\t\t\t\t\t\t\t\tunknownLinks?: string[]\n\t\t\t\t\t\t\t\t\t}> = Array.from({ length: specs.length })\n\n\t\t\t\t\t\t\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\tif (!pkMeta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t\t\t\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t\t\t\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\t\t\t\t\t\t\tvalues: [ids],\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\t\t\t\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t\t\t\t\t\t\tfor (const i of indices) {\n\t\t\t\t\t\t\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\t\t\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\t\t\t\t\t\t\tif (!row) {\n\t\t\t\t\t\t\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\t\t\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\t\t\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\t\t\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t? new Set(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t: null\n\n\t\t\t\t\t\t\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\t\t\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst shouldInclude =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tincludeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod !== 'sync' && !includeSet?.has(linkName)) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetColumns = getSqlColumns(targetMeta)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = linked\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.fieldname) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst fkValue = rowData[link.fieldname]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetPkMeta) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = linked[0] ?? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\t\t\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\t\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\t\t\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\t\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\treturn results\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst doctype = String(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, count: 0 }\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname))\n\t\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection)\n\t\t\t\t\t\t\t\t\t\t\tconst whereClauses: string[] = []\n\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown filter field: ${field} for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(`\"${camelToSnake(field)}\" = $${values.length}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\n\t\t\t\t\t\t\t\t\t\t\t// ORDER BY (field name whitelisted — column names cannot be parameterised)\n\t\t\t\t\t\t\t\t\t\t\tlet orderByClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (typeof spec.orderBy !== 'string')\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`)\n\t\t\t\t\t\t\t\t\t\t\t\tconst orderByStr = spec.orderBy\n\t\t\t\t\t\t\t\t\t\t\t\tconst lastUnder = orderByStr.lastIndexOf('_')\n\t\t\t\t\t\t\t\t\t\t\t\tif (lastUnder <= 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy format: \"${orderByStr}\". Expected FIELD_ASC or FIELD_DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst dir = orderByStr.slice(lastUnder + 1).toUpperCase()\n\t\t\t\t\t\t\t\t\t\t\t\tif (dir !== 'ASC' && dir !== 'DESC') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy direction: \"${dir}\". Must be ASC or DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst fieldName = orderByStr.slice(0, lastUnder)\n\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(fieldName)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown orderBy field: \"${fieldName}\" for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(fieldName)}\" ${dir}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// LIMIT / OFFSET\n\t\t\t\t\t\t\t\t\t\t\tlet pagingClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.limit)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` LIMIT $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.offset)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` OFFSET $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t\t// Total count matching filters (independent of LIMIT/OFFSET)\n\t\t\t\t\t\t\t\t\t\t\tlet count = rows.length\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null || spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst countValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhere: string[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountWhere.push(`\"${camelToSnake(field)}\" = $${countValues.length}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: countRows } = await debugSql<{ row_count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: countValues,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\tcount = parseInt(countRows[0]?.row_count ?? '0', 10)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\treturn { data: rows, doctype, count }\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn sideEffectWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, action: $action, actionArgs: $actionArgs }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, spec: any) => {\n\t\t\t\t\t\t\t\t\tconst meta = getMeta(String(spec.doctype))\n\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\tif (!pkMeta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `No primary key for doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\tconst table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Record envelope: [{ id, data }] — the transition keys off the record id.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract\n\t\t\t\t\t\t\t\t\tconst argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []) as Array<{\n\t\t\t\t\t\t\t\t\t\tid?: string | number\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\tconst recordId = argList[0]?.id\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await applyGuardedTransition(actionDef, {\n\t\t\t\t\t\t\t\t\t\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<{ status: string | null }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT \"status\" FROM ${table} WHERE \"${pkColumn}\"::text = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0]?.status == null ? undefined : rows[0].status\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"status\" = $1 WHERE \"${pkColumn}\"::text = $2`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [nextState, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n}\n\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).\n */\nfunction flattenFields(fields: DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Derive quoted SQL column entries from a flat field array.\n * Skips non-scalar fields (kind !== 'field'), `computed` fields\n * (no backing DB column), and *expanding* links\n * (relations fetched separately, not scalar columns on this table).\n */\nfunction collectColumns(fields: DoctypeField[], links: Map<string, LinkDeclaration>): string[] {\n\tconst columns: string[] = []\n\tfor (const f of flattenFields(fields)) {\n\t\tif (f.kind !== 'field') continue\n\t\t// A computed field has no backing DB column.\n\t\tif (f.computed) continue\n\t\t// Only an *expanding* link is a relation rather than a column. An inline link (a picker)\n\t\t// keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the\n\t\t// shared rule, also used by the client resolver; never re-derive it here.\n\t\tconst link = links.get(f.fieldname)\n\t\tif (link && resolveLinkRenderMode(link, f.component) !== 'inline') continue\n\t\tconst col = camelToSnake(f.fieldname)\n\t\tcolumns.push(col !== f.fieldname ? `\"${col}\" AS \"${f.fieldname}\"` : `\"${f.fieldname}\"`)\n\t}\n\treturn columns\n}\n\n/**\n * Derive a quoted SQL column list from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, then\n * aliases it back to the fieldname so result rows carry API-layer keys.\n * Excludes `computed` fields (no backing DB column), Fieldset\n * containers (recursing into their children instead), and *expanding* links\n * (relations fetched separately). An inline link keeps its FK column here.\n *\n * Exported for unit testing (not re-exported from the package index).\n */\nexport function getSqlColumns(meta: DoctypeMeta): string {\n\tconst links = new Map<string, LinkDeclaration>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinks.set(link.fieldname ?? key, link)\n\t\t}\n\t}\n\treturn collectColumns(meta.fields, links).join(', ')\n}\n\n/**\n * Find the field marked `primaryKey` in the doctype.\n * Returns undefined when none is marked (PK-less doctypes).\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\treturn meta.fields.find((f): f is ValueField => f.kind === 'field' && Boolean(f.primaryKey))\n}\n\n/**\n * Resolve the PostgreSQL FROM clause target for a doctype.\n * Uses the `tables` override map first; falls back to camelToSnake(name).\n * Schema-qualified names (e.g. \"orpin.plan\") are emitted as \"schema\".\"table\".\n * Values must be bare identifiers or schema.table pairs — not SQL fragments.\n */\nfunction resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn `\"${target.slice(0, dotIndex)}\".\"${target.slice(dotIndex + 1)}\"`\n\t}\n\treturn `\"${target}\"`\n}\n","import { wrapPlans } from 'postgraphile/utils'\n\n/**\n * Options for the Stonecrop debug plugin.\n * @public\n */\nexport interface DebugPluginOptions {\n\t/** Log a message when a plan is built for a Stonecrop field. Default: `true` */\n\tlogPlans?: boolean\n\t/** Log timing for plan construction. Default: `false` */\n\tlogTiming?: boolean\n}\n\n/**\n * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with\n * debug logging. Use it in your preset file:\n *\n * ```typescript\n * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * plugins: [createStonecropPlugin(), createDebugPlugin()],\n * }\n * ```\n *\n * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the\n * plugins array so the wrapper sees the Stonecrop fields.\n *\n * @param options - Optional logging configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createDebugPlugin = (options: DebugPluginOptions = {}): GraphileConfig.Plugin => {\n\tconst { logPlans = true, logTiming = false } = options\n\n\tconst wrapField = (typeName: string, fieldName: string) => ({\n\t\tplan: (plan: () => any) => {\n\t\t\tif (logPlans) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] Building plan for ${typeName}.${fieldName}`)\n\t\t\t}\n\n\t\t\tconst start = logTiming ? Date.now() : 0\n\t\t\tconst $result = plan()\n\n\t\t\tif (logTiming) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[@stonecrop/graphql-middleware] Plan built for ${typeName}.${fieldName} in ${Date.now() - start}ms`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn $result\n\t\t},\n\t})\n\n\treturn wrapPlans({\n\t\tQuery: {\n\t\t\tstonecropRecord: wrapField('Query', 'stonecropRecord'),\n\t\t\tstonecropRecords: wrapField('Query', 'stonecropRecords'),\n\t\t\tstonecropMeta: wrapField('Query', 'stonecropMeta'),\n\t\t\tstonecropAllMeta: wrapField('Query', 'stonecropAllMeta'),\n\t\t},\n\t\tMutation: {\n\t\t\tstonecropAction: wrapField('Mutation', 'stonecropAction'),\n\t\t},\n\t})\n}\n","import { PostGraphileAmberPreset } from 'postgraphile/presets/amber'\n\n/**\n * Controls how PostgreSQL column names are mapped to GraphQL field names in the synthesized preset.\n *\n * - `'camel'` (default): `my_column` → `myColumn`. This matches PostGraphile Amber's built-in behaviour.\n * - `'pascal'`: `my_column` → `MyColumn`. Opt in via `createStonecropPreset({ fieldCasing: 'pascal' })` or\n * `grafserv.fieldCasing: 'pascal'` in `nuxt.config.ts`.\n *\n * Smart tag overrides (`@name` on column comments) are respected regardless of this setting.\n * @public\n */\nexport type FieldCasing = 'camel' | 'pascal'\n\nconst StonecropFieldCasingPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropFieldCasingPlugin',\n\tversion: '0.0.0',\n\tinflection: {\n\t\treplace: {\n\t\t\tattribute(previous, options, details) {\n\t\t\t\treturn this.upperCamelCase(this._attributeName(details))\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Creates a Stonecrop-flavoured PostGraphile preset.\n *\n * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's\n * recommended defaults. Pass it to `extends` in your PostGraphile configuration:\n *\n * ```typescript\n * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [createStonecropPreset()],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n *\n * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable\n * `MyColumn`-style field names instead of the default `myColumn` (camelCase).\n * @public\n */\nexport const createStonecropPreset = (options?: { fieldCasing?: FieldCasing }): GraphileConfig.Preset => ({\n\textends: [PostGraphileAmberPreset],\n\tplugins: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],\n})\n\n/**\n * The default Stonecrop PostGraphile preset with camelCase field names.\n *\n * Equivalent to `createStonecropPreset()` with no options. Use this when you\n * do not need to customise field casing:\n *\n * ```typescript\n * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [StonecropPreset],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n * @public\n */\nexport const StonecropPreset: GraphileConfig.Preset = createStonecropPreset()\n"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","direct","getAllMeta","hasMeta","clearRegistry","validateReferences","field","target","key","link","registry","registerFetchHandler","handler","getFetchHandler","clearFetchHandlers","applyGuardedTransition","actionDef","io","currentState","isActionAllowedInState","typeDefs","gql","createStonecropPlugin","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","i","d","results","indices","meta","pkMeta","getPkMeta","pkColumn","camelToSnake","columns","getSqlColumns","ids","rows","resolveTableName","rowByPk","r","specId","row","rowData","recordOptions","includeAll","includeSet","linkName","fetch","isMany","effectiveMethod","effectiveLimit","handlerName","targetMeta","targetColumns","backlinkCol","sql","linkValues","linked","fkValue","targetPkMeta","targetPkColumn","unknownLinks","$filters","$orderBy","$limit","$offset","spec","knownFields","flattenFields","f","values","whereClauses","value","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","table","recordId","nextState","fields","collectColumns","links","resolveLinkRenderMode","col","tables","pascalToSnake","dotIndex","createDebugPlugin","logPlans","logTiming","wrapField","typeName","plan","start","$result","wrapPlans","StonecropFieldCasingPlugin","previous","details","createStonecropPreset","PostGraphileAmberPreset","StonecropPreset"],"mappings":";;;;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AAAA,EAPiB;AAAA,EAEA;AAMlB;AAmBO,SAASG,GAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,GAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,GAAKN,GAAKI,CAAK;AAGhC,IAFaG,GAASF,CAAQ,EAErB,gBACRN,GAAaM,GAAUJ,CAAO,IACpBG,EAAM,SAAS,OAAO,KAChCI,GAAgBH,GAAUJ,CAAO;AAAA,EAEnC;AACD;AAKA,SAASO,GAAgBC,GAAkBR,GAAoC;AAC9E,QAAMS,IAAUC,GAAaF,GAAU,OAAO;AAC9C,MAAIG;AAEJ,MAAI;AACH,IAAAA,I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,QAAM,EAAE,UAAAyI,IAAW,IAAM,WAAAC,IAAY,OAAU1I,GAEzC2I,IAAY,CAACC,GAAkBzB,OAAuB;AAAA,IAC3D,MAAM,CAAC0B,MAAoB;AAC1B,MAAIJ,KAEH,QAAQ,IAAI,qDAAqDG,CAAQ,IAAIzB,CAAS,EAAE;AAGzF,YAAM2B,IAAQJ,IAAY,KAAK,IAAA,IAAQ,GACjCK,IAAUF,EAAA;AAEhB,aAAIH,KAEH,QAAQ;AAAA,QACP,kDAAkDE,CAAQ,IAAIzB,CAAS,OAAO,KAAK,QAAQ2B,CAAK;AAAA,MAAA,GAI3FC;AAAA,IACR;AAAA,EAAA;AAGD,SAAOC,GAAU;AAAA,IAChB,OAAO;AAAA,MACN,iBAAiBL,EAAU,SAAS,iBAAiB;AAAA,MACrD,kBAAkBA,EAAU,SAAS,kBAAkB;AAAA,MACvD,eAAeA,EAAU,SAAS,eAAe;AAAA,MACjD,kBAAkBA,EAAU,SAAS,kBAAkB;AAAA,IAAA;AAAA,IAExD,UAAU;AAAA,MACT,iBAAiBA,EAAU,YAAY,iBAAiB;AAAA,IAAA;AAAA,EACzD,CACA;AACF,GCrDMM,KAAoD;AAAA,EACzD,MAAM;AAAA,EACN,SAAS;AAAA,EACT,YAAY;AAAA,IACX,SAAS;AAAA,MACR,UAAUC,GAAUlJ,GAASmJ,GAAS;AACrC,eAAO,KAAK,eAAe,KAAK,eAAeA,CAAO,CAAC;AAAA,MACxD;AAAA,IAAA;AAAA,EACD;AAEF,GAsBaC,KAAwB,CAACpJ,OAAoE;AAAA,EACzG,SAAS,CAACqJ,EAAuB;AAAA,EACjC,SAASrJ,GAAS,gBAAgB,WAAW,CAACiJ,EAA0B,IAAI,CAAA;AAC7E,IAmBaK,KAAyCF,GAAA;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(typeof data === 'object' && data !== null ? data : {}), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\tconst direct = doctypeRegistry.get(name)\n\tif (direct) return direct\n\t// Fallback: find by slug (links reference doctypes by slug, not name)\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\tif (doctype.slug === name) return doctype\n\t}\n\treturn undefined\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && !doctypeRegistry.has(doctype.inherits)) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && !doctypeRegistry.has(target)) {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'doctype'],\n\t\t\t\t\tmessage: `Link references unknown doctype: ${target}`,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Check link-declaration targets (component-primary links live in the `links` map)\n\t\tif (doctype.links) {\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (!doctypeRegistry.has(link.target)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'target'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${link.target}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { PgClient } from '@dataplan/pg'\nimport type { LinkDeclaration } from '@stonecrop/schema'\n\n/**\n * Handler for a custom fetch strategy on a link declaration.\n * Called during `stonecropRecord` resolution when `link.fetch.method === 'custom'`.\n *\n * @param pgClient - Active database client for the current request\n * @param parentRecord - Resolved parent record (scalar fields already populated)\n * @param link - The link declaration, giving access to cardinality and other metadata\n * @returns A single linked record or an array depending on `link.cardinality`\n * @public\n */\nexport type FetchHandler = (\n\tpgClient: PgClient,\n\tparentRecord: Record<string, unknown>,\n\tlink: LinkDeclaration\n) => Promise<Record<string, unknown> | Record<string, unknown>[]>\n\nconst registry = new Map<string, FetchHandler>()\n\n/**\n * Register a custom fetch handler by name.\n * The name must match the `handler` field on a `CustomFetch` strategy declaration.\n * @public\n */\nexport function registerFetchHandler(name: string, handler: FetchHandler): void {\n\tregistry.set(name, handler)\n}\n\n/**\n * Retrieve a registered fetch handler by name.\n * Returns `undefined` if no handler has been registered under that name.\n * @public\n */\nexport function getFetchHandler(name: string): FetchHandler | undefined {\n\treturn registry.get(name)\n}\n\n/**\n * Remove all registered fetch handlers. Primarily for test isolation.\n * @public\n */\nexport function clearFetchHandlers(): void {\n\tregistry.clear()\n}\n","import { isActionAllowedInState } from '@stonecrop/schema'\n\n/**\n * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.\n * The same guard runs whether the record lives in Postgres, a mock executor, or an\n * in-memory Map — only these two closures change per backend.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/** Read the record's current workflow state (the value of its `status` field), or undefined if unknown. */\n\treadState: () => Promise<string | undefined>\n\t/** Persist the record's new workflow state, written verbatim. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Persist record field data for a mutate-in-place self-transition, returning the full updated\n\t * record (so the client writeback reflects the new data). Optional: a backend with no data-write\n\t * path (e.g. PostGraphile today, which writes only `status`) omits it, and a self-transition is\n\t * then rejected loudly rather than silently dropped.\n\t */\n\twriteData?: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>\n}\n\n/**\n * Apply a workflow action's state transition on the server, enforcing `allowedStates`.\n *\n * The server owns the transition: it reads the record's authoritative current state,\n * rejects the action when `isActionAllowedInState` denies it, then writes `nextState`\n * verbatim. Storage access is injected via `io` so this one guard serves every backend\n * and can never disagree with the frontend's `getAvailableTransitions`, which shares the\n * same predicate.\n *\n * There are three action shapes this guard distinguishes:\n * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\n * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current\n * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.\n * A backend without a data-write path rejects it loudly instead of dropping it silently.\n * - Anything else with no `nextState` and no `selfTransition` flag is a genuine authoring mistake (or a\n * stateless side-effect command whose server handler is not wired — the intended `callHandler` primitive\n * is still unimplemented): it fails loudly before touching the backend rather than reporting a false success.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`\n * @param io - Backend read/write closures\n * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)\n * @returns Action result envelope — the resulting `data.state` for a transition, the full record for a self-transition\n * @public\n */\nexport async function applyGuardedTransition(\n\tactionDef: { label?: string; allowedStates?: string[]; nextState?: string; selfTransition?: boolean },\n\tio: GuardedTransitionIO,\n\tdata?: Record<string, unknown>\n): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\t// A non-self action with no target has nothing to apply — fail loudly WITHOUT touching the backend\n\t// (a stateless command's server handler is not wired; a genuine bug should not read/write anything).\n\tif (!actionDef.selfTransition && actionDef.nextState == null) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" has no workflow transition and no server-side effect is wired — nothing was executed.`,\n\t\t}\n\t}\n\n\tconst currentState = (await io.readState()) ?? ''\n\n\tif (!isActionAllowedInState(actionDef, currentState)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action not allowed from state: ${currentState || '(unknown)'}`,\n\t\t}\n\t}\n\n\t// Self-transition: mutate record data in place, keep the current state. Requires a backend data-write\n\t// capability; without it (e.g. PostGraphile today) reject loudly. The full updated record is returned\n\t// so the client writeback reflects the new data.\n\tif (actionDef.selfTransition) {\n\t\tif (!io.writeData) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" persists record data in place, which this backend does not support.`,\n\t\t\t}\n\t\t}\n\t\tconst record = await io.writeData(data ?? {})\n\t\treturn { success: true, data: record, error: null }\n\t}\n\n\t// NON-ATOMIC: the current state is read above and nextState written here as two\n\t// separate statements. Two concurrent transitions on the same record can both pass\n\t// the guard before either writes, so both \"succeed\" even when the workflow intended\n\t// them to be mutually exclusive. Closing this requires guarding and writing in one\n\t// statement — an atomic `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)`\n\t// — and reporting \"no rows updated\" as a rejected transition. Deferred for now.\n\tif (actionDef.nextState == null) {\n\t\t// Unreachable (guarded above), but keeps `nextState` narrowed to a string below.\n\t\treturn { success: false, data: null, error: 'nothing was executed' }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\treturn {\n\t\tsuccess: true,\n\t\tdata: { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { gql } from 'postgraphile/utils'\n\n/**\n * GraphQL type definitions for Stonecrop's middleware API.\n * Includes stonecropMeta, stonecropRecord, stonecropRecords, stonecropAction, and related types.\n * @public\n */\nexport const typeDefs = gql`\n\ttype StonecropFieldMeta {\n\t\tkind: String!\n\t\tfieldname: String!\n\t\tcomponent: String\n\t\tprimaryKey: Boolean\n\t\tcomputed: Boolean\n\t\tlanguage: String\n\t\tdoctype: String\n\t\tlabel: String\n\t\twidth: String\n\t\talign: String\n\t\tedit: Boolean\n\t\tmask: String\n\t\tformat: String\n\t\tmode: String\n\t\toptions: JSON\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\tvalidation: JSON\n\t\tcardinality: String\n\t\tsource: String\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tnextState: String\n\t\tstateless: Boolean\n\t\tselfTransition: Boolean\n\t\tclientHandler: String\n\t}\n\n\ttype StonecropWorkflowMeta {\n\t\tstates: [String!]\n\t\tactions: [StonecropWorkflowAction!]\n\t}\n\n\ttype StonecropDoctypeMeta {\n\t\tname: String!\n\t\tslug: String\n\t\tfields: [StonecropFieldMeta!]!\n\t\tworkflow: StonecropWorkflowMeta\n\t\tinherits: String\n\t}\n\n\ttype StonecropRecordResult {\n\t\tdata: JSON\n\t\tdoctype: String!\n\t\tunknownLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\tcount: Int!\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\tdata: JSON\n\t\terror: String\n\t}\n\n\textend type Query {\n\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\tstonecropRecord(doctype: String!, id: String!, options: JSON): StonecropRecordResult\n\t\tstonecropRecords(\n\t\t\tdoctype: String!\n\t\t\tfilters: JSON\n\t\t\torderBy: String\n\t\t\tlimit: Int\n\t\t\toffset: Int\n\t\t\toptions: JSON\n\t\t): StonecropRecordsResult\n\t}\n\n\textend type Mutation {\n\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t}\n`\n","import type {\n\tDoctypeField,\n\tDoctypeMeta,\n\tLinkDeclaration,\n\tTableField,\n\tValueField,\n\tGetRecordOptions,\n} from '@stonecrop/schema'\nimport { camelToSnake, getPrimaryKeyField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin.\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/**\n\t * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks\n\t * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.\n\t */\n\tdebug?: boolean\n\t/**\n\t * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.\n\t * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).\n\t * SQL fragments and subqueries are not supported.\n\t * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.\n\t */\n\ttables?: Record<string, string>\n}\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.\n *\n * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`\n * during schema construction — it does not need to be supplied by the caller.\n *\n * @param options - Optional plugin configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions = {}): GraphileConfig.Plugin => {\n\t/**\n\t * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging\n\t * for queries that run inside custom loadOneWithPgClient callbacks, which\n\t * bypass the executor's native instrumentation.\n\t */\n\tconst debugSql = options.debug\n\t\t? <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? [])\n\t\t\t\treturn pgClient.query<T>(query)\n\t\t\t}\n\t\t: <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => pgClient.query<T>(query)\n\n\treturn extendSchema(build => {\n\t\t// Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type\n\t\tconst pgExecutors = (build as any).input?.pgRegistry?.pgExecutors as Record<string, PgExecutor> | undefined\n\t\tconst executor = pgExecutors ? Object.values(pgExecutors)[0] : undefined\n\t\tif (!executor) {\n\t\t\tthrow new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured')\n\t\t}\n\n\t\treturn {\n\t\t\ttypeDefs,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(String(doctype))\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id, $options }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, id: $id, options: $options }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\t\t\t\t\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\t\t\t\t\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\t\t\t\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\t\t\t\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\t\t\t\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst results: Array<{\n\t\t\t\t\t\t\t\t\t\tdata: Record<string, unknown> | null\n\t\t\t\t\t\t\t\t\t\tdoctype: string\n\t\t\t\t\t\t\t\t\t\tunknownLinks?: string[]\n\t\t\t\t\t\t\t\t\t}> = Array.from({ length: specs.length })\n\n\t\t\t\t\t\t\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\tif (!pkMeta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t\t\t\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t\t\t\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\t\t\t\t\t\t\tvalues: [ids],\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\t\t\t\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t\t\t\t\t\t\tfor (const i of indices) {\n\t\t\t\t\t\t\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\t\t\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\t\t\t\t\t\t\tif (!row) {\n\t\t\t\t\t\t\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\t\t\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\t\t\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\t\t\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t? new Set(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t: null\n\n\t\t\t\t\t\t\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\t\t\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst shouldInclude =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tincludeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod !== 'sync' && !includeSet?.has(linkName)) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetColumns = getSqlColumns(targetMeta)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = linked\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.fieldname) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst fkValue = rowData[link.fieldname]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetPkMeta) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = linked[0] ?? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\t\t\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\t\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\t\t\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\t\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\treturn results\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst doctype = String(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, count: 0 }\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname))\n\t\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection)\n\t\t\t\t\t\t\t\t\t\t\tconst whereClauses: string[] = []\n\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown filter field: ${field} for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(`\"${camelToSnake(field)}\" = $${values.length}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\n\t\t\t\t\t\t\t\t\t\t\t// ORDER BY (field name whitelisted — column names cannot be parameterised)\n\t\t\t\t\t\t\t\t\t\t\tlet orderByClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (typeof spec.orderBy !== 'string')\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`)\n\t\t\t\t\t\t\t\t\t\t\t\tconst orderByStr = spec.orderBy\n\t\t\t\t\t\t\t\t\t\t\t\tconst lastUnder = orderByStr.lastIndexOf('_')\n\t\t\t\t\t\t\t\t\t\t\t\tif (lastUnder <= 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy format: \"${orderByStr}\". Expected FIELD_ASC or FIELD_DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst dir = orderByStr.slice(lastUnder + 1).toUpperCase()\n\t\t\t\t\t\t\t\t\t\t\t\tif (dir !== 'ASC' && dir !== 'DESC') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy direction: \"${dir}\". Must be ASC or DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst fieldName = orderByStr.slice(0, lastUnder)\n\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(fieldName)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown orderBy field: \"${fieldName}\" for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(fieldName)}\" ${dir}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// LIMIT / OFFSET\n\t\t\t\t\t\t\t\t\t\t\tlet pagingClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.limit)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` LIMIT $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.offset)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` OFFSET $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t\t// Total count matching filters (independent of LIMIT/OFFSET)\n\t\t\t\t\t\t\t\t\t\t\tlet count = rows.length\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null || spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst countValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhere: string[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountWhere.push(`\"${camelToSnake(field)}\" = $${countValues.length}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: countRows } = await debugSql<{ row_count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: countValues,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\tcount = parseInt(countRows[0]?.row_count ?? '0', 10)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\treturn { data: rows, doctype, count }\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn sideEffectWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, action: $action, actionArgs: $actionArgs }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, spec: any) => {\n\t\t\t\t\t\t\t\t\tconst meta = getMeta(String(spec.doctype))\n\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\tif (!pkMeta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `No primary key for doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\tconst table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Record envelope: [{ id, data }] — the transition keys off the record id.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract\n\t\t\t\t\t\t\t\t\tconst argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []) as Array<{\n\t\t\t\t\t\t\t\t\t\tid?: string | number\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\tconst recordId = argList[0]?.id\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await applyGuardedTransition(actionDef, {\n\t\t\t\t\t\t\t\t\t\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<{ status: string | null }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT \"status\" FROM ${table} WHERE \"${pkColumn}\"::text = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0]?.status == null ? undefined : rows[0].status\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"status\" = $1 WHERE \"${pkColumn}\"::text = $2`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [nextState, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n}\n\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).\n */\nfunction flattenFields(fields: DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Derive quoted SQL column entries from a flat field array.\n * Skips non-scalar fields (kind !== 'field'), `computed` fields\n * (no backing DB column), and *expanding* links\n * (relations fetched separately, not scalar columns on this table).\n */\nfunction collectColumns(fields: DoctypeField[], links: Map<string, LinkDeclaration>): string[] {\n\tconst columns: string[] = []\n\tfor (const f of flattenFields(fields)) {\n\t\tif (f.kind !== 'field') continue\n\t\t// A computed field has no backing DB column.\n\t\tif (f.computed) continue\n\t\t// Only an *expanding* link is a relation rather than a column. An inline link (a picker)\n\t\t// keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the\n\t\t// shared rule, also used by the client resolver; never re-derive it here.\n\t\tconst link = links.get(f.fieldname)\n\t\tif (link && resolveLinkRenderMode(link, f.component) !== 'inline') continue\n\t\tconst col = camelToSnake(f.fieldname)\n\t\tcolumns.push(col !== f.fieldname ? `\"${col}\" AS \"${f.fieldname}\"` : `\"${f.fieldname}\"`)\n\t}\n\treturn columns\n}\n\n/**\n * Derive a quoted SQL column list from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, then\n * aliases it back to the fieldname so result rows carry API-layer keys.\n * Excludes `computed` fields (no backing DB column), Fieldset\n * containers (recursing into their children instead), and *expanding* links\n * (relations fetched separately). An inline link keeps its FK column here.\n *\n * Exported for unit testing (not re-exported from the package index).\n */\nexport function getSqlColumns(meta: DoctypeMeta): string {\n\tconst links = new Map<string, LinkDeclaration>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinks.set(link.fieldname ?? key, link)\n\t\t}\n\t}\n\treturn collectColumns(meta.fields, links).join(', ')\n}\n\n/**\n * Find the field marked `primaryKey` in the doctype.\n * Returns undefined when none is marked (PK-less doctypes).\n *\n * Delegates to `@stonecrop/schema` so the server's identity predicate and the client's record\n * keying resolve the same field — this used to be a private re-implementation of that rule.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\treturn getPrimaryKeyField(meta.fields)\n}\n\n/**\n * Resolve the PostgreSQL FROM clause target for a doctype.\n * Uses the `tables` override map first; falls back to camelToSnake(name).\n * Schema-qualified names (e.g. \"orpin.plan\") are emitted as \"schema\".\"table\".\n * Values must be bare identifiers or schema.table pairs — not SQL fragments.\n */\nfunction resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn `\"${target.slice(0, dotIndex)}\".\"${target.slice(dotIndex + 1)}\"`\n\t}\n\treturn `\"${target}\"`\n}\n","import { wrapPlans } from 'postgraphile/utils'\n\n/**\n * Options for the Stonecrop debug plugin.\n * @public\n */\nexport interface DebugPluginOptions {\n\t/** Log a message when a plan is built for a Stonecrop field. Default: `true` */\n\tlogPlans?: boolean\n\t/** Log timing for plan construction. Default: `false` */\n\tlogTiming?: boolean\n}\n\n/**\n * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with\n * debug logging. Use it in your preset file:\n *\n * ```typescript\n * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * plugins: [createStonecropPlugin(), createDebugPlugin()],\n * }\n * ```\n *\n * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the\n * plugins array so the wrapper sees the Stonecrop fields.\n *\n * @param options - Optional logging configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createDebugPlugin = (options: DebugPluginOptions = {}): GraphileConfig.Plugin => {\n\tconst { logPlans = true, logTiming = false } = options\n\n\tconst wrapField = (typeName: string, fieldName: string) => ({\n\t\tplan: (plan: () => any) => {\n\t\t\tif (logPlans) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] Building plan for ${typeName}.${fieldName}`)\n\t\t\t}\n\n\t\t\tconst start = logTiming ? Date.now() : 0\n\t\t\tconst $result = plan()\n\n\t\t\tif (logTiming) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[@stonecrop/graphql-middleware] Plan built for ${typeName}.${fieldName} in ${Date.now() - start}ms`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn $result\n\t\t},\n\t})\n\n\treturn wrapPlans({\n\t\tQuery: {\n\t\t\tstonecropRecord: wrapField('Query', 'stonecropRecord'),\n\t\t\tstonecropRecords: wrapField('Query', 'stonecropRecords'),\n\t\t\tstonecropMeta: wrapField('Query', 'stonecropMeta'),\n\t\t\tstonecropAllMeta: wrapField('Query', 'stonecropAllMeta'),\n\t\t},\n\t\tMutation: {\n\t\t\tstonecropAction: wrapField('Mutation', 'stonecropAction'),\n\t\t},\n\t})\n}\n","import { PostGraphileAmberPreset } from 'postgraphile/presets/amber'\n\n/**\n * Controls how PostgreSQL column names are mapped to GraphQL field names in the synthesized preset.\n *\n * - `'camel'` (default): `my_column` → `myColumn`. This matches PostGraphile Amber's built-in behaviour.\n * - `'pascal'`: `my_column` → `MyColumn`. Opt in via `createStonecropPreset({ fieldCasing: 'pascal' })` or\n * `grafserv.fieldCasing: 'pascal'` in `nuxt.config.ts`.\n *\n * Smart tag overrides (`@name` on column comments) are respected regardless of this setting.\n * @public\n */\nexport type FieldCasing = 'camel' | 'pascal'\n\nconst StonecropFieldCasingPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropFieldCasingPlugin',\n\tversion: '0.0.0',\n\tinflection: {\n\t\treplace: {\n\t\t\tattribute(previous, options, details) {\n\t\t\t\treturn this.upperCamelCase(this._attributeName(details))\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Creates a Stonecrop-flavoured PostGraphile preset.\n *\n * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's\n * recommended defaults. Pass it to `extends` in your PostGraphile configuration:\n *\n * ```typescript\n * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [createStonecropPreset()],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n *\n * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable\n * `MyColumn`-style field names instead of the default `myColumn` (camelCase).\n * @public\n */\nexport const createStonecropPreset = (options?: { fieldCasing?: FieldCasing }): GraphileConfig.Preset => ({\n\textends: [PostGraphileAmberPreset],\n\tplugins: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],\n})\n\n/**\n * The default Stonecrop PostGraphile preset with camelCase field names.\n *\n * Equivalent to `createStonecropPreset()` with no options. Use this when you\n * do not need to customise field casing:\n *\n * ```typescript\n * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [StonecropPreset],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n * @public\n */\nexport const StonecropPreset: GraphileConfig.Preset = createStonecropPreset()\n"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","direct","getAllMeta","hasMeta","clearRegistry","validateReferences","field","target","key","link","registry","registerFetchHandler","handler","getFetchHandler","clearFetchHandlers","applyGuardedTransition","actionDef","io","currentState","isActionAllowedInState","typeDefs","gql","createStonecropPlugin","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","i","d","results","indices","meta","pkMeta","getPkMeta","pkColumn","camelToSnake","columns","getSqlColumns","ids","rows","resolveTableName","rowByPk","r","specId","row","rowData","recordOptions","includeAll","includeSet","linkName","fetch","isMany","effectiveMethod","effectiveLimit","handlerName","targetMeta","targetColumns","backlinkCol","sql","linkValues","linked","fkValue","targetPkMeta","targetPkColumn","unknownLinks","$filters","$orderBy","$limit","$offset","spec","knownFields","flattenFields","f","values","whereClauses","value","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","table","recordId","nextState","fields","collectColumns","links","resolveLinkRenderMode","col","getPrimaryKeyField","tables","pascalToSnake","dotIndex","createDebugPlugin","logPlans","logTiming","wrapField","typeName","plan","start","$result","wrapPlans","StonecropFieldCasingPlugin","previous","details","createStonecropPreset","PostGraphileAmberPreset","StonecropPreset"],"mappings":";;;;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AAAA,EAPiB;AAAA,EAEA;AAMlB;AAmBO,SAASG,GAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,GAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,GAAKN,GAAKI,CAAK;AAGhC,IAFaG,GAASF,CAAQ,EAErB,gBACRN,GAAaM,GAAUJ,CAAO,IACpBG,EAAM,SAAS,OAAO,KAChCI,GAAgBH,GAAUJ,CAAO;AAAA,EAEnC;AACD;AAKA,SAASO,GAAgBC,GAAkBR,GAAoC;AAC9E,QAAMS,IAAUC,GAAaF,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Snake, resolveLinkRenderMode } from '@stonecrop/schema';
|
|
2
2
|
import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
|
|
3
3
|
import { constant, lambda, object } from 'postgraphile/grafast';
|
|
4
4
|
import { extendSchema } from 'postgraphile/utils';
|
|
@@ -404,9 +404,12 @@ export function getSqlColumns(meta) {
|
|
|
404
404
|
/**
|
|
405
405
|
* Find the field marked `primaryKey` in the doctype.
|
|
406
406
|
* Returns undefined when none is marked (PK-less doctypes).
|
|
407
|
+
*
|
|
408
|
+
* Delegates to `@stonecrop/schema` so the server's identity predicate and the client's record
|
|
409
|
+
* keying resolve the same field — this used to be a private re-implementation of that rule.
|
|
407
410
|
*/
|
|
408
411
|
function getPkMeta(meta) {
|
|
409
|
-
return meta.fields
|
|
412
|
+
return getPrimaryKeyField(meta.fields);
|
|
410
413
|
}
|
|
411
414
|
/**
|
|
412
415
|
* Resolve the PostgreSQL FROM clause target for a doctype.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stonecrop/graphql-middleware",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.5",
|
|
4
4
|
"description": "GraphQL middleware for PostGraphile and Stonecrop schema",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"graphql": "^16.14.0",
|
|
24
24
|
"pluralize": "^8.0.0",
|
|
25
25
|
"postgraphile": "^5.0.3",
|
|
26
|
-
"@stonecrop/schema": "0.16.
|
|
26
|
+
"@stonecrop/schema": "0.16.5"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@electric-sql/pglite": "^0.4.5",
|