@stonecrop/graphql-middleware 0.58.4 → 0.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.js +188 -62
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -172,7 +172,7 @@ Actions are declared per doctype in `workflow.actions`. Each action names the st
|
|
|
172
172
|
}
|
|
173
173
|
```
|
|
174
174
|
|
|
175
|
-
The `stonecropAction(doctype, action, args)` mutation dispatches through `applyGuardedTransition`: it reads the record's `status`, rejects the action if the current state is not in `allowedStates` (`isActionAllowedInState`), then writes `nextState`. The record is identified by `args[0].id`. A self-transition (`selfTransition: true`) keeps the state and writes the record's data instead: the Postgres adapter sets each declared field that has a column,
|
|
175
|
+
The `stonecropAction(doctype, action, args)` mutation dispatches through `applyGuardedTransition`: it reads the record's `status`, rejects the action if the current state is not in `allowedStates` (`isActionAllowedInState`), then writes `nextState`. The record is identified by `args[0].id`. A self-transition (`selfTransition: true`) keeps the state and writes the record's data instead: the Postgres adapter sets each declared field that has a column and whose value differs from the stored record, encoding a JSON, list, range or composite value in the shape its read serves (a string for a JSON column is JSON text), and refuses a value of the wrong shape, naming the field ([ADR 0011](docs/decisions/0011-save-writes-what-changed.md)). It never sets `status`, a column the database fills itself (a generated column, or an identity generated always) or a linked record sent for a link's key, and lists each key it left out in `droppedFields`. When a server-side handler is registered for the self-transition (`actionHandlers`), the handler does that write instead, creating the record too, and must return the record it saved.
|
|
176
176
|
|
|
177
177
|
An action against a record that does not exist is reported as such, before the guard runs. This depends on the backend distinguishing the two things `undefined` used to mean — `GuardedTransitionIO.readState` returns `null` for a lookup that missed, and `undefined` only for a row that exists with no workflow state. A backend that returns `undefined` for both makes a bad id look like a workflow violation, or, when the action declares no `allowedStates`, makes it look like a success.
|
|
178
178
|
|
package/dist/index.js
CHANGED
|
@@ -459,6 +459,79 @@ function resolveTableName(name, tables) {
|
|
|
459
459
|
// src/columns.ts
|
|
460
460
|
/** A domain's underlying type, through any domains stacked on it. */
|
|
461
461
|
var baseCodec = (codec) => codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec;
|
|
462
|
+
var DATE_TIME_TYPES = /* @__PURE__ */ new Set([
|
|
463
|
+
TYPES.date,
|
|
464
|
+
TYPES.timestamp,
|
|
465
|
+
TYPES.timestamptz
|
|
466
|
+
]);
|
|
467
|
+
var GEOMETRIC_TYPES = /* @__PURE__ */ new Set([
|
|
468
|
+
TYPES.point,
|
|
469
|
+
TYPES.lseg,
|
|
470
|
+
TYPES.box,
|
|
471
|
+
TYPES.path,
|
|
472
|
+
TYPES.polygon,
|
|
473
|
+
TYPES.circle
|
|
474
|
+
]);
|
|
475
|
+
/** Whether a type's value is read as an object: JSON, a composite, a range or a geometric type. */
|
|
476
|
+
var readsAsObject = (codec) => codec === TYPES.json || codec === TYPES.jsonb || Boolean(codec.attributes) || Boolean(codec.rangeOfCodec) || GEOMETRIC_TYPES.has(codec);
|
|
477
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
478
|
+
var hasExactly = (value, keys) => Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
|
|
479
|
+
/** Whether `value` has the shape a read of `codec` serves, so that encoding it cannot write some other value. */
|
|
480
|
+
var fitsShape = (codec, value) => {
|
|
481
|
+
if (value === null) return true;
|
|
482
|
+
const base = baseCodec(codec);
|
|
483
|
+
if (base === TYPES.json || base === TYPES.jsonb) return true;
|
|
484
|
+
const { arrayOfCodec, rangeOfCodec, attributes } = base;
|
|
485
|
+
if (arrayOfCodec) return Array.isArray(value) && value.every((entry) => fitsShape(arrayOfCodec, entry));
|
|
486
|
+
if (rangeOfCodec) {
|
|
487
|
+
const fitsBound = (bound) => bound === null || isRecord(bound) && hasExactly(bound, ["value", "inclusive"]) && typeof bound.inclusive === "boolean" && bound.value !== null && fitsShape(rangeOfCodec, bound.value);
|
|
488
|
+
return isRecord(value) && hasExactly(value, ["start", "end"]) && fitsBound(value.start) && fitsBound(value.end);
|
|
489
|
+
}
|
|
490
|
+
if (attributes) return isRecord(value) && hasExactly(value, Object.keys(attributes)) && Object.entries(attributes).every(([name, attribute]) => fitsShape(attribute.codec, value[name]));
|
|
491
|
+
return GEOMETRIC_TYPES.has(base) ? isRecord(value) : typeof value !== "object";
|
|
492
|
+
};
|
|
493
|
+
var fields = (composite) => Object.keys(composite.attributes ?? {}).join(", ");
|
|
494
|
+
/** The shape a read of `codec` serves, as a refusal names it. */
|
|
495
|
+
var shapeOf = (codec) => {
|
|
496
|
+
const base = baseCodec(codec);
|
|
497
|
+
if (base.arrayOfCodec) {
|
|
498
|
+
const element = baseCodec(base.arrayOfCodec);
|
|
499
|
+
if (element.rangeOfCodec) return "a list of ranges, each with a start and an end";
|
|
500
|
+
if (element.attributes) return `a list of objects, each with exactly the fields ${fields(element)}`;
|
|
501
|
+
return readsAsObject(element) ? "a list" : "a list of single values";
|
|
502
|
+
}
|
|
503
|
+
if (base.rangeOfCodec) return "a range with a start and an end";
|
|
504
|
+
if (base.attributes) return `an object with exactly the fields ${fields(base)}`;
|
|
505
|
+
return GEOMETRIC_TYPES.has(base) ? "an object" : "a single value, not an object";
|
|
506
|
+
};
|
|
507
|
+
/** The cast for one date or time range, or `undefined` for any other type. */
|
|
508
|
+
var dateRangeCast = (codec) => {
|
|
509
|
+
const bound = baseCodec(codec).rangeOfCodec;
|
|
510
|
+
const castFromPg = bound && DATE_TIME_TYPES.has(baseCodec(bound)) ? baseCodec(bound).castFromPg : void 0;
|
|
511
|
+
if (!castFromPg) return void 0;
|
|
512
|
+
const edge = (fragment) => sql`case when isfinite(${fragment}) then ${castFromPg(fragment)} else ${fragment}::text end`;
|
|
513
|
+
return (range) => sql`case when ${range} is null then null else json_build_array(lower_inc(${range}), ${edge(sql`lower(${range})`)}, ${edge(sql`upper(${range})`)}, upper_inc(${range}))::text end`;
|
|
514
|
+
};
|
|
515
|
+
/**
|
|
516
|
+
* The select of a date or time range, or a list of them, keeping an infinite bound as the text Postgres
|
|
517
|
+
* writes for it (`-infinity`) and a NULL range as null. Not PostGraphile's own cast, which reads an
|
|
518
|
+
* infinite bound as no bound and a NULL range as one with no bounds, so a save of the read would write
|
|
519
|
+
* `[-infinity, …)` back as `(, …)`. Bounds stay zone-free.
|
|
520
|
+
*/
|
|
521
|
+
var dateRangeSelect = (codec, columnSql) => {
|
|
522
|
+
const rangeCast = dateRangeCast(codec);
|
|
523
|
+
if (rangeCast) return rangeCast(columnSql);
|
|
524
|
+
const element = baseCodec(codec).arrayOfCodec;
|
|
525
|
+
const elementCast = element && dateRangeCast(element);
|
|
526
|
+
if (!elementCast) return void 0;
|
|
527
|
+
const range = sql.identifier(Symbol("range"));
|
|
528
|
+
return sql`case when ${columnSql} is null then null else array(select ${elementCast(range)} from unnest(${columnSql}) as ${range})::text end`;
|
|
529
|
+
};
|
|
530
|
+
/**
|
|
531
|
+
* Temporal writes a negative duration signed as a whole (`-P1DT1H`), which Postgres refuses; Postgres
|
|
532
|
+
* reads the sign on each part (`P-1DT-1H`).
|
|
533
|
+
*/
|
|
534
|
+
var signEachPart = (duration) => duration.startsWith("-P") ? duration.slice(1).replace(/\d+(?:\.\d+)?(?=[YMWDHS])/g, "-$&") : duration;
|
|
462
535
|
/**
|
|
463
536
|
* The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which
|
|
464
537
|
* names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast
|
|
@@ -480,42 +553,44 @@ var momentConversion = (codec) => {
|
|
|
480
553
|
codec: LIST_TYPES.timestamptz
|
|
481
554
|
};
|
|
482
555
|
};
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
"months",
|
|
486
|
-
"days",
|
|
487
|
-
"hours",
|
|
488
|
-
"minutes",
|
|
489
|
-
"seconds"
|
|
490
|
-
];
|
|
556
|
+
/** An interval as PostGraphile's cast writes it, `to_char(…, 'YYYY_MM_DD_HH24_MI_SS.US')`, each part signed apart. */
|
|
557
|
+
var INTERVAL_TEXT = /^(-?\d+)_(-?\d+)_(-?\d+)_(-?\d+)_(-?\d+)_(-?\d+)\.(-?\d+)$/;
|
|
491
558
|
/**
|
|
492
|
-
* An interval, as PostGraphile
|
|
493
|
-
* a duration field holds whatever the backend, as a day is `YYYY-MM-DD`.
|
|
494
|
-
*
|
|
559
|
+
* An interval, as PostGraphile's cast writes it, read as an ISO 8601 duration (`P1DT2H30M`): the value
|
|
560
|
+
* a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Postgres writes an ISO 8601
|
|
561
|
+
* duration back natively.
|
|
562
|
+
*
|
|
563
|
+
* Parsed here, not by PostGraphile's codec, which reads a second and a half less (`-01.-500000`) as -1 s.
|
|
495
564
|
*
|
|
496
565
|
* Postgres signs each part apart, so it can hold "a day less an hour", which no ISO 8601 duration can.
|
|
497
566
|
* Such an interval throws rather than being read as some other length.
|
|
498
567
|
*/
|
|
499
|
-
var isoDuration = (
|
|
500
|
-
const
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const parts =
|
|
568
|
+
var isoDuration = (text, describe) => {
|
|
569
|
+
const match = INTERVAL_TEXT.exec(text);
|
|
570
|
+
if (!match) throw new Error(`${describe()} is an interval in a form this reader does not know.`);
|
|
571
|
+
const [years, months, days, hours, minutes, seconds, fraction] = match.slice(1).map(Number);
|
|
572
|
+
const microseconds = seconds * 1e6 + fraction;
|
|
573
|
+
const parts = [
|
|
574
|
+
years,
|
|
575
|
+
months,
|
|
576
|
+
days,
|
|
577
|
+
hours,
|
|
578
|
+
minutes,
|
|
579
|
+
microseconds
|
|
580
|
+
];
|
|
505
581
|
if (parts.some((value) => value > 0) && parts.some((value) => value < 0)) throw new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`);
|
|
506
|
-
const microseconds = Math.round(part("seconds") * 1e6);
|
|
507
582
|
return Temporal.Duration.from({
|
|
508
|
-
years
|
|
509
|
-
months
|
|
510
|
-
days
|
|
511
|
-
hours
|
|
512
|
-
minutes
|
|
583
|
+
years,
|
|
584
|
+
months,
|
|
585
|
+
days,
|
|
586
|
+
hours,
|
|
587
|
+
minutes,
|
|
513
588
|
seconds: Math.trunc(microseconds / 1e6),
|
|
514
589
|
milliseconds: Math.trunc(microseconds % 1e6 / 1e3),
|
|
515
590
|
microseconds: microseconds % 1e3
|
|
516
591
|
}).toString();
|
|
517
592
|
};
|
|
518
|
-
var readIntervalList = (
|
|
593
|
+
var readIntervalList = (text, describe) => LIST_TYPES.text.fromPg(text).map((interval) => interval === null ? null : isoDuration(interval, describe));
|
|
519
594
|
/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */
|
|
520
595
|
var intervalShape = (codec) => {
|
|
521
596
|
if (baseCodec(codec) === TYPES.interval) return "one";
|
|
@@ -524,9 +599,10 @@ var intervalShape = (codec) => {
|
|
|
524
599
|
/**
|
|
525
600
|
* Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each
|
|
526
601
|
* value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is
|
|
527
|
-
* `2026-01-01`.
|
|
528
|
-
* the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`)
|
|
529
|
-
*
|
|
602
|
+
* `2026-01-01`. Three exceptions: a `timestamp`, or a list of them, served as the moment each names in
|
|
603
|
+
* the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`); an `interval`, or
|
|
604
|
+
* a list of them, served as an ISO 8601 duration (see `isoDuration`); and a date or time range, or a
|
|
605
|
+
* list of them, keeping its infinite bounds and a NULL (see `dateRangeSelect`).
|
|
530
606
|
*
|
|
531
607
|
* Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,
|
|
532
608
|
* which names another day or hour outside UTC, and a save writes that shifted value back. Not a
|
|
@@ -565,12 +641,12 @@ function createColumnReader(codecs, executor, tables) {
|
|
|
565
641
|
const conversion = momentConversion(columnCodec);
|
|
566
642
|
const readCodec = conversion?.codec ?? columnCodec;
|
|
567
643
|
const columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column);
|
|
568
|
-
const cast = readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`;
|
|
644
|
+
const cast = dateRangeSelect(columnCodec, columnSql) ?? readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`;
|
|
569
645
|
const compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`);
|
|
570
646
|
if (compiled.values.length > 0) throw new Error(`The codec for ${table}."${column}" casts with a bound value, which this adapter cannot select.`);
|
|
571
647
|
const shape = intervalShape(columnCodec);
|
|
572
648
|
const describe = (text) => () => `"${alias}" from ${table} (${text})`;
|
|
573
|
-
decoders.set(alias, shape === "one" ? (text) => isoDuration(
|
|
649
|
+
decoders.set(alias, shape === "one" ? (text) => isoDuration(text, describe(text)) : shape === "list" ? (text) => readIntervalList(text, describe(text)) : readCodec.fromPg);
|
|
574
650
|
return compiled.text;
|
|
575
651
|
}).join(", "),
|
|
576
652
|
decodeRows(rows) {
|
|
@@ -587,6 +663,23 @@ function createColumnReader(codecs, executor, tables) {
|
|
|
587
663
|
const conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec);
|
|
588
664
|
return conversion ? `${placeholder}::${conversion.type}` : placeholder;
|
|
589
665
|
},
|
|
666
|
+
encode(doctype, column, value) {
|
|
667
|
+
if (value === null) return { value };
|
|
668
|
+
const columnCodec = findAttribute(doctype, findTableCodec(doctype), column).codec;
|
|
669
|
+
const codec = baseCodec(columnCodec);
|
|
670
|
+
if (codec === TYPES.line) return { refused: "is a line, which cannot be saved" };
|
|
671
|
+
if (codec === TYPES.json || codec === TYPES.jsonb) return { value: typeof value === "string" ? value : codec.toPg(value) };
|
|
672
|
+
if (!fitsShape(codec, value)) return { refused: `must be ${shapeOf(codec)}` };
|
|
673
|
+
if (codec.arrayOfCodec) {
|
|
674
|
+
if (baseCodec(codec.arrayOfCodec) === TYPES.interval && Array.isArray(value)) {
|
|
675
|
+
const durations = value.map((entry) => typeof entry === "string" ? signEachPart(entry) : entry);
|
|
676
|
+
return { value: LIST_TYPES.text.toPg(durations) };
|
|
677
|
+
}
|
|
678
|
+
return { value: (momentConversion(columnCodec)?.codec ?? codec).toPg(value) };
|
|
679
|
+
}
|
|
680
|
+
if (codec === TYPES.interval && typeof value === "string") return { value: signEachPart(value) };
|
|
681
|
+
return readsAsObject(codec) ? { value: codec.toPg(value) } : { value };
|
|
682
|
+
},
|
|
590
683
|
writable(doctype, column) {
|
|
591
684
|
const { extensions } = findAttribute(doctype, findTableCodec(doctype), column);
|
|
592
685
|
return extensions?.isInsertable !== false || extensions?.isUpdatable !== false;
|
|
@@ -776,11 +869,12 @@ var typeDefs = gql`
|
|
|
776
869
|
"""
|
|
777
870
|
record: JSON
|
|
778
871
|
"""
|
|
779
|
-
Keys the write discarded because the doctype declares no column for them,
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
872
|
+
Keys the write discarded because the doctype declares no column for them, because the
|
|
873
|
+
field is the workflow state, which only a transition moves, because the database fills the
|
|
874
|
+
column itself, or because the value was a linked record rather than the link's key. Null
|
|
875
|
+
when everything sent was stored. The action still succeeded — this is what it did not
|
|
876
|
+
keep, and a client that reports an unqualified success without checking it tells the user
|
|
877
|
+
data was saved that was not.
|
|
784
878
|
"""
|
|
785
879
|
droppedFields: [String!]
|
|
786
880
|
}
|
|
@@ -837,6 +931,37 @@ var LINK_FK_ALIAS = "__stonecropLinkFk_";
|
|
|
837
931
|
* reads.
|
|
838
932
|
*/
|
|
839
933
|
var STATE_COLUMN = "status";
|
|
934
|
+
/** Whether a link finds its rows by a column on the target, rather than by a key on this record. */
|
|
935
|
+
var isManySide = (link) => link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
|
|
936
|
+
/**
|
|
937
|
+
* The key column of each expanding one-side link, under its `LINK_FK_ALIAS` alias. A many-side link
|
|
938
|
+
* finds its rows by a column on the target, and an inline link keeps its key as a scalar that
|
|
939
|
+
* `getColumnSelections` already selects under its own name.
|
|
940
|
+
*/
|
|
941
|
+
function linkKeySelections(meta) {
|
|
942
|
+
const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
|
|
943
|
+
return Object.entries(meta.links ?? {}).flatMap(([linkName, link]) => {
|
|
944
|
+
const fieldname = link.fieldname ?? linkName;
|
|
945
|
+
if (isManySide(link) || resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") return [];
|
|
946
|
+
return [{
|
|
947
|
+
fieldname,
|
|
948
|
+
column: camelToSnake(fieldname),
|
|
949
|
+
alias: `${LINK_FK_ALIAS}${fieldname}`
|
|
950
|
+
}];
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Whether two values are the same JSON value: object keys in any order, list items in order, and no
|
|
955
|
+
* coercion (`"5"` is not `5`).
|
|
956
|
+
*/
|
|
957
|
+
var sameJsonValue = (left, right) => {
|
|
958
|
+
if (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((entry, index) => sameJsonValue(entry, right[index]));
|
|
959
|
+
if (left !== null && typeof left === "object" && right !== null && typeof right === "object") {
|
|
960
|
+
const leftKeys = Object.keys(left);
|
|
961
|
+
return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.hasOwn(right, key) && sameJsonValue(Reflect.get(left, key), Reflect.get(right, key)));
|
|
962
|
+
}
|
|
963
|
+
return left === right;
|
|
964
|
+
};
|
|
840
965
|
/**
|
|
841
966
|
* Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
|
|
842
967
|
*
|
|
@@ -889,20 +1014,8 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
889
1014
|
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
890
1015
|
const ids = indices.map((i) => String(specs[i].id));
|
|
891
1016
|
const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
|
|
892
|
-
const linkFkAliases =
|
|
893
|
-
|
|
894
|
-
if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
|
|
895
|
-
const fieldname = link.fieldname ?? linkName;
|
|
896
|
-
if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
|
|
897
|
-
linkFkAliases.push({
|
|
898
|
-
fieldname,
|
|
899
|
-
alias: `${LINK_FK_ALIAS}${fieldname}`
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases.map(({ fieldname, alias }) => ({
|
|
903
|
-
column: camelToSnake(fieldname),
|
|
904
|
-
alias
|
|
905
|
-
}))]);
|
|
1017
|
+
const linkFkAliases = linkKeySelections(meta);
|
|
1018
|
+
const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases]);
|
|
906
1019
|
const { rows } = await debugSql(pgClient, {
|
|
907
1020
|
text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
|
|
908
1021
|
values: [ids]
|
|
@@ -930,7 +1043,7 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
930
1043
|
if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
|
|
931
1044
|
const fieldname = link.fieldname ?? linkName;
|
|
932
1045
|
const fetch = link.fetch;
|
|
933
|
-
const isMany = link
|
|
1046
|
+
const isMany = isManySide(link);
|
|
934
1047
|
const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
|
|
935
1048
|
const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
|
|
936
1049
|
const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
|
|
@@ -1116,20 +1229,25 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1116
1229
|
const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
|
|
1117
1230
|
const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
|
|
1118
1231
|
const droppedFields = [];
|
|
1119
|
-
const
|
|
1232
|
+
const linkFields = /* @__PURE__ */ new Set([...flattenFields$1(meta.fields).filter((field) => field.kind === "field" && Boolean(field.doctype)).map((field) => field.fieldname), ...Object.entries(meta.links ?? {}).filter(([, link]) => !isManySide(link)).map(([linkName, link]) => link.fieldname ?? linkName)]);
|
|
1233
|
+
const partitionPatch = (patch, stored) => {
|
|
1120
1234
|
const cols = [];
|
|
1121
1235
|
const values = [];
|
|
1122
1236
|
for (const [key, value] of Object.entries(patch)) {
|
|
1123
|
-
|
|
1237
|
+
const column = camelToSnake(key);
|
|
1238
|
+
if (!writable.has(key) || !columns.writable(meta.name, column)) {
|
|
1124
1239
|
droppedFields.push(key);
|
|
1125
1240
|
continue;
|
|
1126
1241
|
}
|
|
1127
|
-
if (value !== null && typeof value === "object") {
|
|
1242
|
+
if (linkFields.has(key) && value !== null && typeof value === "object") {
|
|
1128
1243
|
droppedFields.push(key);
|
|
1129
1244
|
continue;
|
|
1130
1245
|
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1246
|
+
if (stored instanceof Object && Object.hasOwn(stored, key) && sameJsonValue(Reflect.get(stored, key), value)) continue;
|
|
1247
|
+
const encoded = columns.encode(meta.name, column, value);
|
|
1248
|
+
if ("refused" in encoded) throw new Error(`${actionDef.label ?? spec.action} failed: "${key}" ${encoded.refused}.`);
|
|
1249
|
+
cols.push(column);
|
|
1250
|
+
values.push(encoded.value);
|
|
1133
1251
|
}
|
|
1134
1252
|
return {
|
|
1135
1253
|
cols,
|
|
@@ -1161,9 +1279,9 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1161
1279
|
});
|
|
1162
1280
|
},
|
|
1163
1281
|
writeData: async (patch, exists) => {
|
|
1164
|
-
const { cols, values } = partitionPatch(patch);
|
|
1165
1282
|
const returning = columns.select(meta.name, getColumnSelections(meta));
|
|
1166
1283
|
if (!exists) {
|
|
1284
|
+
const { cols, values } = partitionPatch(patch);
|
|
1167
1285
|
const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
|
|
1168
1286
|
const { rows } = await debugSql(tx, {
|
|
1169
1287
|
text,
|
|
@@ -1172,14 +1290,22 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1172
1290
|
returning.decodeRows(rows);
|
|
1173
1291
|
return rows[0] ?? {};
|
|
1174
1292
|
}
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1293
|
+
const linkKeys = linkKeySelections(meta);
|
|
1294
|
+
const storedSelect = columns.select(meta.name, [...getColumnSelections(meta), ...linkKeys]);
|
|
1295
|
+
const { rows: storedRows } = await debugSql(tx, {
|
|
1296
|
+
text: `SELECT ${storedSelect.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
|
|
1297
|
+
values: [String(recordId)]
|
|
1298
|
+
});
|
|
1299
|
+
storedSelect.decodeRows(storedRows);
|
|
1300
|
+
const stored = storedRows[0] ?? {};
|
|
1301
|
+
const compared = { ...stored };
|
|
1302
|
+
for (const { fieldname, alias } of linkKeys) {
|
|
1303
|
+
compared[fieldname] = stored[alias];
|
|
1304
|
+
delete compared[alias];
|
|
1305
|
+
delete stored[alias];
|
|
1182
1306
|
}
|
|
1307
|
+
const { cols, values } = partitionPatch(patch, JSON.parse(JSON.stringify(compared)));
|
|
1308
|
+
if (cols.length === 0) return stored;
|
|
1183
1309
|
const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
|
|
1184
1310
|
const { rows } = await debugSql(tx, {
|
|
1185
1311
|
text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["flattenFields","flattenFields","flattenFields"],"sources":["../src/fields.ts","../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/tables.ts","../src/columns.ts","../src/link-display.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import type { DoctypeField, ValueField } from '@stonecrop/schema'\nimport { flattenFields } from '@stonecrop/schema'\n\n// Re-exported so this module stays the one place the adapter asks about a doctype's fields, while\n// the definition itself lives in `@stonecrop/schema`. It moved there because `DoctypeMeta`'s own\n// validation needs the same descent, and the copy it had written instead scanned top level only —\n// so the load gate and the read path disagreed about what a doctype declares, which is exactly\n// what keeping one definition is for.\nexport { flattenFields }\n\n/**\n * The fields that have a database column of their own — the one definition of that question.\n *\n * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is\n * declared precisely to state it has no column, and a container (a table field) is a relation\n * rather than a value. Everything else names a column.\n *\n * This is deliberately **not** the same question as \"does this column belong in a record payload\".\n * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`\n * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the\n * two is how the read path came to drop the very column its expansion needed. Callers wanting the\n * payload projection filter this further by render mode; callers asking whether a column exists —\n * link validation, and the write path deciding what it may set — want it unfiltered.\n *\n * Extracted because the rule had grown three statements across two modules, one of them a comment\n * reading \"mirrors `collectColumns`\". A rule that has to be mirrored by hand is one edit away from\n * the read path and the validator disagreeing about what a doctype declares.\n */\nexport function columnBackedFields(fields: readonly DoctypeField[]): ValueField[] {\n\treturn flattenFields(fields).filter((f): f is ValueField => f.kind === 'field' && !f.computed)\n}\n","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\nimport { columnBackedFields, flattenFields } from '../fields'\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 doctype references — link targets, `inherits`, and each link's binding — against what\n * is loaded.\n *\n * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by\n * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as\n * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for\n * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.\n * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same\n * question the runtime asks.\n *\n * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers\n * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the\n * permissive direction.\n *\n * The **binding** checks are the same defect class as an unresolvable target, one step further in:\n * a link whose target resolves can still name no way to reach the rows, and the reader's answer for\n * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely\n * empty. Both halves of a declaration are `.optional()` in the schema because which one is required\n * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.\n *\n * Only what the runtime actually consults is required. A `backlink` naming a column the target\n * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;\n * the check exists for the silent cases, not to restate the database's own errors.\n *\n * A many-side link's `orderBy` is the exception, because the doctypes alone can decide it: it names\n * a field of the target, which must have a column. A misspelt one fails every read and save of this\n * doctype, and the read's error names the target rather than this link, so it is refused here, once.\n * The read keeps its own check for doctypes loaded after the schema is built. A one-side link reads\n * one row, so its `orderBy` would be ignored without a word, custom or not. A custom many-side link's\n * order is its handler's to apply, so it is not checked.\n *\n * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that\n * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only\n * meaningful after this module's own loaders have run.\n *\n * @internal\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 && getMeta(doctype.inherits) === undefined) {\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\tconst fields = flattenFields(doctype.fields)\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && getMeta(target) === undefined) {\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\tconst declared = new Set(fields.map(f => f.fieldname))\n\t\t\t// A foreign key is read from a column, so a link can only bind to a field that has one.\n\t\t\t// The rule itself lives in one place — see `columnBackedFields` — because the read path,\n\t\t\t// the write path and this check all have to answer it the same way.\n\t\t\tconst columnBacked = new Set(columnBackedFields(doctype.fields).map(f => f.fieldname))\n\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (getMeta(link.target) === undefined) {\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\n\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\t\t// One row has no order, however it is fetched, so a one-side link's `orderBy` would be\n\t\t\t\t// ignored without a word.\n\t\t\t\tif (!isMany && link.orderBy) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'orderBy'],\n\t\t\t\t\t\tmessage: `Link \"${key}\" is ${link.cardinality} and reads one row, so its \\`orderBy\\` is never read. Remove it.`,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// A custom fetch strategy hands the whole read to its handler, which is given the\n\t\t\t\t// row and the declaration and finds the target however it likes, in the order it\n\t\t\t\t// likes. The runtime returns before consulting either binding below, or the order,\n\t\t\t\t// so requiring one would refuse a link that works.\n\t\t\t\tif (link.fetch?.method === 'custom') continue\n\n\t\t\t\t// The two cardinalities bind through different halves of the declaration, so the\n\t\t\t\t// check has to split the same way the reader does.\n\t\t\t\tif (isMany) {\n\t\t\t\t\t// Many-side: the target rows are found by a column on the *target* table, so\n\t\t\t\t\t// this doctype needs no field of its own — and the in-repo hosts disagree on\n\t\t\t\t\t// whether one exists, which is why only `backlink` can be required here.\n\t\t\t\t\tif (!link.backlink) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'backlink'],\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t`Link \"${key}\" is ${link.cardinality} but names no \\`backlink\\`, so the runtime cannot ` +\n\t\t\t\t\t\t\t\t`find the target rows and drops the link with no error. Name the field on \"${link.target}\" ` +\n\t\t\t\t\t\t\t\t`that points back to this doctype.`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst order = link.orderBy\n\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\tif (\n\t\t\t\t\t\torder &&\n\t\t\t\t\t\ttargetMeta &&\n\t\t\t\t\t\t!columnBackedFields(targetMeta.fields).some(f => f.fieldname === order.fieldname)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst targetDeclares = flattenFields(targetMeta.fields).some(f => f.fieldname === order.fieldname)\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'orderBy', 'fieldname'],\n\t\t\t\t\t\t\tmessage: targetDeclares\n\t\t\t\t\t\t\t\t? `Link \"${key}\" orders its rows by \"${order.fieldname}\", which has no database column on ` +\n\t\t\t\t\t\t\t\t\t`\"${link.target}\" (it is computed, or a container rather than a value), so every read of ` +\n\t\t\t\t\t\t\t\t\t`this doctype fails. Order by a field with a column.`\n\t\t\t\t\t\t\t\t: `Link \"${key}\" orders its rows by \"${order.fieldname}\", which \"${link.target}\" does not ` +\n\t\t\t\t\t\t\t\t\t`declare, so every read of this doctype fails. Name a field of \"${link.target}\".`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// One-side: the foreign key is a column on *this* table, read as\n\t\t\t\t// `link.fieldname ?? key`. A name matching no declared field is not selected, so the\n\t\t\t\t// link resolves to null forever and reads as \"this record has no such relation\".\n\t\t\t\tconst fieldname = link.fieldname ?? key\n\t\t\t\tif (!columnBacked.has(fieldname)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\t// Point at whichever half actually carries the binding: the `fieldname`\n\t\t\t\t\t\t// property when it is set, otherwise the key itself. Naming `target` here\n\t\t\t\t\t\t// would send the reader to the one part that resolved correctly.\n\t\t\t\t\t\tpath: link.fieldname ? [doctype.name, 'links', key, 'fieldname'] : [doctype.name, 'links', key],\n\t\t\t\t\t\t// Two different repairs, so two different diagnoses: a name nothing declares\n\t\t\t\t\t\t// is a typo, while a name that resolves to a column-less field is a binding\n\t\t\t\t\t\t// pointed at the wrong one of several real fields.\n\t\t\t\t\t\tmessage: declared.has(fieldname)\n\t\t\t\t\t\t\t? `Link \"${key}\" binds to field \"${fieldname}\", which has no database column of its own — ` +\n\t\t\t\t\t\t\t\t`it is computed, or a container rather than a value — so there is no foreign key to read ` +\n\t\t\t\t\t\t\t\t`and the record read fails on the missing column. Bind the link to the field holding the ` +\n\t\t\t\t\t\t\t\t`foreign key.`\n\t\t\t\t\t\t\t: `Link \"${key}\" binds to field \"${fieldname}\", which this doctype does not declare, so it ` +\n\t\t\t\t\t\t\t\t`resolves to null with no error. Declare that field, or set \\`fieldname\\` to the field ` +\n\t\t\t\t\t\t\t\t`holding the foreign key. (A link's key is its fieldname unless \\`fieldname\\` overrides it.)`,\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 * The storage calls `applyGuardedTransition` makes. Each backend supplies its own.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/**\n\t * Read the record's workflow state: its state, `undefined` when it exists with no state, or\n\t * `null` when there is no such record. Return `null`, not `undefined`, for a missing record, or\n\t * an action on it can report success while writing nothing.\n\t *\n\t * For a self-transition sent with an id that matches no record, throw instead: the record was\n\t * deleted since it was read, and creating it would report a lost update as a success.\n\t */\n\treadState: () => Promise<string | null | undefined>\n\t/** Write the record's new workflow state. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Save a self-transition's field data and return the whole record, including its key. When\n\t * `exists` is false, create the record: take its key from `patch` for a natural-keyed doctype,\n\t * or mint one. An empty return for a create fails the action.\n\t *\n\t * Optional: without it, a self-transition fails unless `runEffect` is supplied. Never called\n\t * when `runEffect` is supplied.\n\t */\n\twriteData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>\n\t/**\n\t * Run the server-side handler registered for this action, once it passes its `allowedStates`\n\t * check (a self-transition creating a record skips that check), and before the state is\n\t * written. A stateless command fails without one.\n\t *\n\t * Its return becomes the result's `data`. On a self-transition it is the whole save, on a record\n\t * not created yet too, and must return the record it saved or the action fails. Throwing fails\n\t * the action; undoing what it wrote is the backend's job (the Postgres adapter runs each action\n\t * in a transaction).\n\t *\n\t * @param currentState - The state `readState` returned (`''` for a record with no state), or\n\t * `undefined` when it was not read or the record does not exist yet\n\t */\n\trunEffect?: (currentState: string | undefined) => Promise<unknown>\n}\n\n/**\n * Run a workflow action on the server: check `allowedStates`, then apply the action through `io`.\n *\n * - A **transition** (`nextState`) runs `io.runEffect` if supplied, then writes the new state.\n *\n * - A **self-transition** (`selfTransition`, such as Save) saves the record's data and keeps its\n * state, through `io.runEffect` if supplied and `io.writeData` otherwise.\n *\n * - A **stateless command** (neither) runs `io.runEffect` and leaves the state alone.\n *\n * - Anything else fails without touching the backend.\n *\n * On a record that does not exist yet, a self-transition creates it without checking\n * `allowedStates`, a command with no `allowedStates` runs, and anything else fails: the actions\n * `isActionAllowedOnNewRecord` allows. On a saved record the check is the same rule the client's\n * `getAvailableTransitions` uses.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and `nextState` or `selfTransition`\n * @param io - The backend's storage calls\n * @param data - The record's field data, for a self-transition\n * @returns Whether the action succeeded, the record or state it produced, and any error\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\tconst label = actionDef.label ?? 'unknown'\n\tconst isSelfTransition = actionDef.selfTransition === true\n\tconst hasStateOutcome = isSelfTransition || actionDef.nextState != null\n\n\t// A throw is attributed to the action by name: the adapter's handler is code the doctype\n\t// author cannot see, so an anonymous failure would be undebuggable from either side.\n\tconst runEffect = async (effect: NonNullable<GuardedTransitionIO['runEffect']>, currentState: string | undefined) => {\n\t\ttry {\n\t\t\treturn { ran: true as const, result: await effect(currentState) }\n\t\t} catch (err) {\n\t\t\tconst error = `Action \"${label}\" failed: ${err instanceof Error ? err.message : String(err)}`\n\t\t\treturn { ran: false as const, failure: { success: false, data: null, error } }\n\t\t}\n\t}\n\n\t// A self-transition with an effect: the effect is the write, on a new record and a saved one\n\t// alike, and owes the record it saved, as `writeData` does.\n\tconst saveThroughEffect = async (\n\t\teffect: NonNullable<GuardedTransitionIO['runEffect']>,\n\t\tcurrentState: string | undefined\n\t) => {\n\t\tconst effectOutcome = await runEffect(effect, currentState)\n\t\tif (!effectOutcome.ran) return effectOutcome.failure\n\t\tconst record = effectOutcome.result\n\t\tif (record === null || typeof record !== 'object' || Array.isArray(record) || Object.keys(record).length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `${label} failed: the server did not return the saved record.`,\n\t\t\t}\n\t\t}\n\t\treturn { success: true, data: record, error: null }\n\t}\n\n\t// Nothing to apply and no effect registered — fail loudly WITHOUT touching the backend.\n\t// This is the honest report for both causes: an action authored with no outcome, and a\n\t// command whose server handler the adapter never registered.\n\tif (!hasStateOutcome && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`,\n\t\t}\n\t}\n\n\t// A self-transition exists to persist data; with no way at all to do that — no data write, no\n\t// create, no effect — reject before running anything rather than half-applying.\n\tif (isSelfTransition && !io.writeData && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" persists record data in place, which this backend does not support.`,\n\t\t}\n\t}\n\n\t// Read the authoritative state only when something actually consumes it: the guard, or a\n\t// state outcome that the caller's readState is paired with. A handler-only command on a\n\t// doctype with no `status` column must not be forced through a read it never uses.\n\tconst isGuarded = (actionDef.allowedStates?.length ?? 0) > 0\n\tlet currentState: string | undefined\n\tif (isGuarded || hasStateOutcome) {\n\t\tconst state = await io.readState()\n\t\t// A missing record is reported, never guarded around. Reaching the guard with a state of\n\t\t// `''` produced two wrong answers depending only on whether the action declared\n\t\t// `allowedStates`: a misleading \"not allowed from state: (unknown)\" when it did, and a\n\t\t// silent `{ success: true }` writing nothing when it did not.\n\t\tif (state === null) {\n\t\t\t// A self-transition against a record that is not there is a create — the same write,\n\t\t\t// against a row that does not exist yet. The guard is deliberately skipped:\n\t\t\t// `allowedStates` constrains movement between states, and a record being created is not\n\t\t\t// in one; its initial state is the backend's to set.\n\t\t\tif (isSelfTransition && io.runEffect) return saveThroughEffect(io.runEffect, undefined)\n\t\t\tif (isSelfTransition && io.writeData) {\n\t\t\t\tconst created = await io.writeData(data ?? {}, false)\n\t\t\t\t// A backend that only knows how to patch returns nothing here, having matched no\n\t\t\t\t// row. Reporting that as success is the exact bug the `null` answer above exists to\n\t\t\t\t// kill, so it must not come back through the create path.\n\t\t\t\tif (!created || Object.keys(created).length === 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: `Action \"${label}\" targets a record that does not exist, and the backend did not create it.`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { success: true, data: created, error: null }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" targets a record that does not exist — nothing was executed.`,\n\t\t\t}\n\t\t}\n\t\tcurrentState = state ?? ''\n\t}\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. The full updated\n\t// record is returned so a created record's identity is known. Never `writeData` after an\n\t// effect: the effect is the write, and a second one would put the form's values back over it.\n\tif (isSelfTransition) {\n\t\tif (io.runEffect) return saveThroughEffect(io.runEffect, currentState)\n\t\tconst record = await io.writeData?.(data ?? {}, true)\n\t\treturn { success: true, data: record ?? null, error: null }\n\t}\n\n\t// The effect runs after the guard and before any write, so a handler that rejects cannot\n\t// leave the record in the target state.\n\tlet effectResult: unknown\n\tif (io.runEffect) {\n\t\tconst effect = await runEffect(io.runEffect, currentState)\n\t\tif (!effect.ran) return effect.failure\n\t\teffectResult = effect.result\n\t}\n\n\t// The state is read above and written here as two calls, with any effect between them. A\n\t// backend must hold the record between the two, or two concurrent transitions can both pass\n\t// the guard; the Postgres adapter does, by reading with FOR UPDATE inside the action's\n\t// transaction.\n\tif (actionDef.nextState == null) {\n\t\t// A stateless command: the effect (guaranteed present by the top guard) is the whole\n\t\t// outcome. It must not move the record — that is the doctype's call, not the handler's.\n\t\treturn { success: true, data: effectResult ?? null, error: null }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\t// The freshest thing the backend produced wins: a handler that returned a record describes\n\t// the row better than the state alone, which is all a bare transition knows.\n\treturn {\n\t\tsuccess: true,\n\t\tdata: effectResult ?? { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { pascalToSnake } from '@stonecrop/schema'\n\n/** A table a doctype reads from, as named before quoting. `schema` is absent for an unqualified name. */\nexport interface TableRef {\n\tschema?: string\n\tname: string\n}\n\n/**\n * The table a doctype reads from: the `tables` override when the adapter supplies one, otherwise the\n * doctype name snake-cased.\n *\n * The one definition of that mapping. It lives in its own module rather than beside either caller\n * because the plugin imports the link-display enrichment, so the enrichment cannot import back —\n * and the copy it made instead was byte-identical, which is the state a mapping is in right before\n * one side learns about schema-qualified names and the other does not.\n *\n * A dotted override is read as `schema.table`, so a table in a non-default Postgres schema keeps\n * its schema instead of becoming one name containing a dot.\n */\nexport function resolveTable(name: string, tables?: Record<string, string>): TableRef {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn { schema: target.slice(0, dotIndex), name: target.slice(dotIndex + 1) }\n\t}\n\treturn { name: target }\n}\n\n/** The quoted SQL table a doctype reads from (see `resolveTable`). */\nexport function resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst table = resolveTable(name, tables)\n\treturn table.schema === undefined ? `\"${table.name}\"` : `\"${table.schema}\".\"${table.name}\"`\n}\n","import { LIST_TYPES, TYPES } from '@dataplan/pg'\nimport type { PgCodec, PgCodecAttribute, PgExecutor } from '@dataplan/pg'\nimport { sql } from 'postgraphile/pg-sql2'\nimport type { SQL } from 'postgraphile/pg-sql2'\nimport { Temporal } from 'temporal-polyfill'\n\nimport { resolveTable, resolveTableName } from './tables'\n\n/** A column to read, and the key its value comes back under. */\nexport interface ColumnSelection {\n\tcolumn: string\n\talias: string\n}\n\n/** One doctype's table, with a select list whose values read as PostGraphile reads them. */\nexport interface ColumnSelect {\n\t/** The quoted table. */\n\ttable: string\n\t/** Each column cast to text the way PostGraphile casts it, under its alias. */\n\tlist: string\n\t/** Decodes every selected value in place with the codec PostGraphile decodes it with. */\n\tdecodeRows(rows: readonly Record<string, unknown>[]): void\n}\n\n/** Builds the select list for a doctype's columns, and the SQL that binds a value to one. */\nexport interface ColumnReader {\n\tselect(doctype: string, selections: readonly ColumnSelection[]): ColumnSelect\n\t/** `placeholder` as the value for `column`, cast where the column needs its value converted. */\n\tbind(doctype: string, column: string, placeholder: string): string\n\t/** Whether a write may set `column`: not one the database fills itself, which PostGraphile marks as neither insertable nor updatable. */\n\twritable(doctype: string, column: string): boolean\n}\n\n/** A domain's underlying type, through any domains stacked on it. */\nconst baseCodec = (codec: PgCodec): PgCodec => (codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec)\n\n/** How a column whose values carry no zone is converted into the moments they name. */\ninterface MomentConversion {\n\t/** The type Postgres converts it to, through the database's zone. */\n\ttype: 'timestamptz' | 'timestamptz[]'\n\tcastSql: SQL\n\t/** Reads the converted value as PostGraphile reads that type. */\n\tcodec: PgCodec\n}\n\n/**\n * The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which\n * names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast\n * Postgres itself makes through the database's zone, so a value leaves as a moment and a moment\n * comes back to the same reading. Every other column needs none.\n *\n * Not PostGraphile's own text for it: that carries no zone, so a browser reads it in its own zone\n * and sends back UTC, and every save moved the stored time by the user's offset.\n */\nconst momentConversion = (codec: PgCodec): MomentConversion | undefined => {\n\tif (baseCodec(codec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz', castSql: sql`::timestamptz`, codec: TYPES.timestamptz }\n\t}\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz[]', castSql: sql`::timestamptz[]`, codec: LIST_TYPES.timestamptz }\n\t}\n\treturn undefined\n}\n\nconst INTERVAL_PARTS = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] as const\n\n/**\n * An interval, as PostGraphile decodes it, written as an ISO 8601 duration (`P1DT2H30M`): the value\n * a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Not PostGraphile's object,\n * which every other backend would have to imitate. Postgres writes an ISO 8601 duration back natively.\n *\n * Postgres signs each part apart, so it can hold \"a day less an hour\", which no ISO 8601 duration can.\n * Such an interval throws rather than being read as some other length.\n */\nconst isoDuration = (interval: unknown, describe: () => string): string => {\n\tconst part = (name: (typeof INTERVAL_PARTS)[number]) => {\n\t\tconst value: unknown = interval instanceof Object ? Reflect.get(interval, name) : undefined\n\t\treturn typeof value === 'number' ? value : 0\n\t}\n\tconst parts = INTERVAL_PARTS.map(part)\n\tif (parts.some(value => value > 0) && parts.some(value => value < 0)) {\n\t\tthrow new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`)\n\t}\n\tconst microseconds = Math.round(part('seconds') * 1e6)\n\treturn Temporal.Duration.from({\n\t\tyears: part('years'),\n\t\tmonths: part('months'),\n\t\tdays: part('days'),\n\t\thours: part('hours'),\n\t\tminutes: part('minutes'),\n\t\tseconds: Math.trunc(microseconds / 1e6),\n\t\tmilliseconds: Math.trunc((microseconds % 1e6) / 1e3),\n\t\tmicroseconds: microseconds % 1e3,\n\t}).toString()\n}\n\nconst readIntervalList = (intervals: unknown, describe: () => string): unknown =>\n\tArray.isArray(intervals)\n\t\t? intervals.map((interval: unknown) => (interval === null ? null : isoDuration(interval, describe)))\n\t\t: intervals\n\n/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */\nconst intervalShape = (codec: PgCodec): 'one' | 'list' | undefined => {\n\tif (baseCodec(codec) === TYPES.interval) return 'one'\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.interval) return 'list'\n\treturn undefined\n}\n\n/**\n * Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each\n * value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is\n * `2026-01-01`. Two exceptions: a `timestamp`, or a list of them, served as the moment each names in\n * the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`), and an\n * `interval`, or a list of them, served as an ISO 8601 duration (see `isoDuration`).\n *\n * Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,\n * which names another day or hour outside UTC, and a save writes that shifted value back. Not a\n * process-wide `setTypeParser` either, which changes every other `pg` query in the host.\n */\nexport function createColumnReader(\n\tcodecs: Readonly<Record<string, PgCodec>>,\n\texecutor: PgExecutor,\n\ttables?: Record<string, string>\n): ColumnReader {\n\tconst tableCodecsByName = new Map<string, PgCodec[]>()\n\tfor (const codec of Object.values(codecs)) {\n\t\tconst pg = codec.extensions?.pg\n\t\tif (!codec.attributes || !codec.extensions?.isTableLike || !pg || codec.executor !== executor) continue\n\t\ttableCodecsByName.set(pg.name, [...(tableCodecsByName.get(pg.name) ?? []), codec])\n\t}\n\n\tconst findTableCodec = (doctype: string): PgCodec => {\n\t\tconst table = resolveTable(doctype, tables)\n\t\tconst matches = (tableCodecsByName.get(table.name) ?? []).filter(\n\t\t\tcodec => table.schema === undefined || codec.extensions?.pg?.schemaName === table.schema\n\t\t)\n\t\tif (matches.length === 1) return matches[0]\n\t\tconst quoted = resolveTableName(doctype, tables)\n\t\tif (matches.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" reads ${quoted}, which PostGraphile has not introspected, so its columns ` +\n\t\t\t\t\t`cannot be read the way PostGraphile reads them. Add the table's schema to the pgService, ` +\n\t\t\t\t\t`or map the doctype in \\`tables\\` to a table PostGraphile knows.`\n\t\t\t)\n\t\t}\n\t\tconst schemas = matches.map(codec => codec.extensions?.pg?.schemaName).join(', ')\n\t\tthrow new Error(\n\t\t\t`Doctype \"${doctype}\" reads ${quoted}, a name PostGraphile knows in more than one schema ` +\n\t\t\t\t`(${schemas}). Map the doctype in \\`tables\\` to \"schema.table\".`\n\t\t)\n\t}\n\n\tconst findAttribute = (doctype: string, tableCodec: PgCodec, column: string): PgCodecAttribute => {\n\t\tconst attribute = tableCodec.attributes?.[column]\n\t\tif (!attribute) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" declares a field for column \"${column}\", which ${resolveTableName(doctype, tables)} does not have.`\n\t\t\t)\n\t\t}\n\t\treturn attribute\n\t}\n\n\treturn {\n\t\tselect(doctype, selections) {\n\t\t\tconst tableCodec = findTableCodec(doctype)\n\t\t\tconst table = resolveTableName(doctype, tables)\n\t\t\t// Keyed by alias, so a column selected twice under one key is decoded once, as `pg` keeps one.\n\t\t\tconst decoders = new Map<string, (value: string) => unknown>()\n\t\t\tconst list = selections\n\t\t\t\t.map(({ column, alias }) => {\n\t\t\t\t\tconst columnCodec = findAttribute(doctype, tableCodec, column).codec\n\t\t\t\t\tconst conversion = momentConversion(columnCodec)\n\t\t\t\t\tconst readCodec = conversion?.codec ?? columnCodec\n\t\t\t\t\tconst columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column)\n\t\t\t\t\tconst cast = readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`\n\t\t\t\t\tconst compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`)\n\t\t\t\t\t// This list is spliced into SQL whose placeholders the caller numbers, so a cast carrying\n\t\t\t\t\t// its own `$1` would silently bind the caller's first value.\n\t\t\t\t\tif (compiled.values.length > 0) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The codec for ${table}.\"${column}\" casts with a bound value, which this adapter cannot select.`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst shape = intervalShape(columnCodec)\n\t\t\t\t\tconst describe = (text: string) => () => `\"${alias}\" from ${table} (${text})`\n\t\t\t\t\tdecoders.set(\n\t\t\t\t\t\talias,\n\t\t\t\t\t\tshape === 'one'\n\t\t\t\t\t\t\t? text => isoDuration(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t: shape === 'list'\n\t\t\t\t\t\t\t\t? text => readIntervalList(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t\t: readCodec.fromPg\n\t\t\t\t\t)\n\t\t\t\t\treturn compiled.text\n\t\t\t\t})\n\t\t\t\t.join(', ')\n\n\t\t\treturn {\n\t\t\t\ttable,\n\t\t\t\tlist,\n\t\t\t\tdecodeRows(rows) {\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tfor (const [alias, fromPg] of decoders) {\n\t\t\t\t\t\t\tconst value = row[alias]\n\t\t\t\t\t\t\tif (value === null) continue\n\t\t\t\t\t\t\t// The list casts every column to text, so anything else is a row this select did not\n\t\t\t\t\t\t\t// produce, or one decoded already.\n\t\t\t\t\t\t\tif (typeof value !== 'string') {\n\t\t\t\t\t\t\t\tthrow new Error(`\"${alias}\" from ${table} is ${typeof value}, not the text its select returns.`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow[alias] = fromPg(value)\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\n\t\tbind(doctype, column, placeholder) {\n\t\t\tconst conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec)\n\t\t\treturn conversion ? `${placeholder}::${conversion.type}` : placeholder\n\t\t},\n\n\t\twritable(doctype, column) {\n\t\t\tconst { extensions } = findAttribute(doctype, findTableCodec(doctype), column)\n\t\t\treturn extensions?.isInsertable !== false || extensions?.isUpdatable !== false\n\t\t},\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema'\nimport type { PgClient } from '@dataplan/pg'\n\nimport type { ColumnReader } from './columns'\nimport { getMeta } from './registry/doctypes'\n\ntype SqlQueryFn = (\n\tpgClient: PgClient,\n\tquery: { text: string; values?: unknown[] }\n) => Promise<{ rows: readonly Record<string, unknown>[] }>\n\ninterface LinkDisplaySpec {\n\tfieldname: string\n\tdisplayField: string\n\ttargetPkFieldname: string\n\ttargetDoctype: string\n}\n\n/**\n * Normalize a scalar SQL cell value to a non-empty string, or nothing.\n *\n * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key\n * in the result, and the display text stamped into the payload. Rejecting objects is what each\n * of those wants: an object FK is a link that was already expanded, and an object display column\n * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it\n * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.\n */\nfunction scalarText(value: unknown): string | undefined {\n\tif (value == null || typeof value === 'object') return undefined\n\tif (typeof value === 'string') return value === '' ? undefined : value\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn undefined\n}\n\nfunction collectLinkDisplaySpecs(meta: DoctypeMeta): LinkDisplaySpec[] {\n\tconst specs: LinkDisplaySpec[] = []\n\n\tfor (const field of flattenFields(meta.fields)) {\n\t\tif (field.kind !== 'field' || !field.doctype) continue\n\n\t\tconst targetMeta = getMeta(field.doctype)\n\t\tif (!targetMeta) continue\n\n\t\t// `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`\n\t\t// makes at the load gate, so a nomination that parsed is one this can build a SELECT from.\n\t\t// A hand-rolled scan here admitted `computed` fields, whose column does not exist.\n\t\tconst displayField = getDisplayField(targetMeta.fields, targetMeta.displayField)\n\t\tif (!displayField) continue\n\n\t\tspecs.push({\n\t\t\tfieldname: field.fieldname,\n\t\t\tdisplayField: displayField.fieldname,\n\t\t\ttargetPkFieldname: getRecordIdField(targetMeta.fields),\n\t\t\ttargetDoctype: targetMeta.name,\n\t\t})\n\t}\n\n\treturn specs\n}\n\n/**\n * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a\n * `displayField`. Expanded relations (object values) are skipped.\n *\n * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch\n * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the\n * loader exists to prevent, and does so invisibly, since the result is identical either way.\n */\nexport async function enrichLinkDisplayFields(\n\tpgClient: PgClient,\n\tmeta: DoctypeMeta,\n\trows: Record<string, unknown>[],\n\tcolumns: ColumnReader,\n\tdebugSql: SqlQueryFn\n): Promise<void> {\n\tconst specs = collectLinkDisplaySpecs(meta)\n\tif (specs.length === 0 || rows.length === 0) return\n\n\tawait Promise.all(\n\t\tspecs.map(async spec => {\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = scalarText(row[spec.fieldname])\n\t\t\t\tif (id !== undefined) ids.add(id)\n\t\t\t}\n\t\t\tif (ids.size === 0) return\n\n\t\t\tconst pkColumn = camelToSnake(spec.targetPkFieldname)\n\t\t\tconst select = columns.select(spec.targetDoctype, [\n\t\t\t\t{ column: pkColumn, alias: spec.targetPkFieldname },\n\t\t\t\t{ column: camelToSnake(spec.displayField), alias: spec.displayField },\n\t\t\t])\n\n\t\t\tconst { rows: displayRows } = await debugSql(pgClient, {\n\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\tvalues: [Array.from(ids)],\n\t\t\t})\n\t\t\tselect.decodeRows(displayRows)\n\n\t\t\tconst displayById = new Map<string, string>()\n\t\t\tfor (const displayRow of displayRows) {\n\t\t\t\tconst key = scalarText(displayRow[spec.targetPkFieldname])\n\t\t\t\tconst text = scalarText(displayRow[spec.displayField])\n\t\t\t\tif (key === undefined || text === undefined) continue\n\t\t\t\tdisplayById.set(key, text)\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst rawId = row[spec.fieldname]\n\t\t\t\tconst idKey = scalarText(rawId)\n\t\t\t\tif (idKey === undefined) continue\n\t\t\t\tconst displayText = displayById.get(idKey)\n\t\t\t\tif (displayText === undefined) continue\n\t\t\t\trow[spec.fieldname] = { id: rawId, displayText }\n\t\t\t}\n\t\t})\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\theight: 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\tparts: 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\tconfig: JSON\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\tdisplayField: 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\t\"\"\"\n\t\tFields whose linked rows were cut short by a row cap, so data holds a prefix of the\n\t\trelation rather than all of it. Null when nothing was truncated. A link cannot be paged,\n\t\tso a client that sees a name here must not write that relation back — the rows it never\n\t\treceived would be deleted.\n\t\t\"\"\"\n\t\ttruncatedLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\t\"\"\"\n\t\tWhether further records exist beyond this page. Always answered — it is read from the\n\t\tpage itself (one extra row is requested and discarded), so it costs no second query.\n\t\t\"\"\"\n\t\thasMore: Boolean!\n\t\t\"\"\"\n\t\tTotal matching the filters, ignoring limit/offset. Null unless the query asked for it\n\t\twith includeTotal, because counting is a full scan on most backends.\n\t\t\"\"\"\n\t\tcount: Int\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\t\"\"\"\n\t\tWhat the action's registered handler returned, verbatim, or the outcome the doctype declared.\n\t\t\"\"\"\n\t\tdata: JSON\n\t\terror: String\n\t\t\"\"\"\n\t\tThe record as stonecropRecord returns it after the action, whoever wrote it. The client stores\n\t\tthis, never data. Null when the action failed or targets no record.\n\t\t\"\"\"\n\t\trecord: JSON\n\t\t\"\"\"\n\t\tKeys the write discarded because the doctype declares no column for them, or because the\n\t\tvalue was a nested relation rather than a column value. Null when everything sent was\n\t\tstored. The action still succeeded — this is what it did not keep, and a client that\n\t\treports an unqualified success without checking it tells the user data was saved that\n\t\twas not.\n\t\t\"\"\"\n\t\tdroppedFields: [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\tincludeTotal: Boolean\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 { DoctypeField, DoctypeMeta, LinkDeclaration, ValueField, GetRecordOptions } from '@stonecrop/schema'\nimport { camelToSnake, getRecordIdField, resolveLinkRenderMode, unwrapInlineLinks } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgCodec, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { createColumnReader } from '../columns'\nimport type { ColumnSelection } from '../columns'\nimport { columnBackedFields, flattenFields } from '../fields'\nimport { enrichLinkDisplayFields } from '../link-display'\nimport { resolveTableName } from '../tables'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta, validateReferences } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Everything a server-side action handler is given when `stonecropAction` dispatches to it.\n *\n * A context object rather than positional parameters so the set can grow without breaking\n * registered handlers — the adapters that supply these live in consumer repositories.\n * @public\n */\nexport interface ActionHandlerContext {\n\t/**\n\t * The database client for this action, inside the action's transaction: throwing rolls back\n\t * everything the handler wrote, and returning commits it.\n\t *\n\t * Never run `BEGIN` or `COMMIT` on it, which would commit work the action may still reject (a\n\t * `SAVEPOINT` undoes part of your work), and never open another connection, whose work would\n\t * not roll back. Its rows carry snake_case column names: return camelCase field names, by\n\t * aliasing in SQL or with `snakeToCamel` from `@stonecrop/schema` (ADR 0004).\n\t */\n\tpgClient: PgClient\n\t/** The doctype the action was dispatched against, as the client sent it. */\n\tdoctype: string\n\t/** The action's key in `workflow.actions` — the same string the handler was registered under. */\n\taction: string\n\t/** The resolved doctype metadata, for field names, the primary key, and the workflow. */\n\tmeta: DoctypeMeta\n\t/** The record's key from the request. Absent for a record not created yet, and for a command on no record. */\n\trecordId?: string | number\n\t/**\n\t * The record field data the client sent (`args[0].data`).\n\t *\n\t * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has\n\t * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist\n\t * the fields the action is allowed to touch.\n\t */\n\tdata: Record<string, unknown>\n\t/** The full argument envelope, for the actions that need more than the first record. */\n\targs: unknown[]\n\t/** The state the guard read (`''` for a record with no state), or `undefined` when nothing required reading it or the record does not exist yet. */\n\tcurrentState?: string\n}\n\n/**\n * A server-side handler for one doctype action, registered in `actionHandlers`.\n *\n * Throwing fails the action and rolls back what it wrote. The return becomes the result's `data`,\n * so use camelCase field names (ADR 0007). The client stores the record read back afterwards, by\n * the doctype's key in this return or else by the request's id.\n * @public\n */\nexport type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>\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 `pascalToSnake(doctype.name)`, so\n\t * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a\n\t * PascalCase name: `camelToSnake('User')` is `_user`.)\n\t */\n\ttables?: Record<string, string>\n\t/**\n\t * Server-side handlers for workflow actions, keyed by the doctype's `name` (not its slug), then\n\t * the action's key. A handler runs only once the action passes its `allowedStates` check, which a\n\t * Save creating a record skips. A stateless command (no `nextState`, no `selfTransition`) fails\n\t * without one, and a transition's runs before the new state is written.\n\t *\n\t * A Save's (`selfTransition`) handler is the whole save: it runs on a record not created yet\n\t * too, with no `recordId`, and must return the record it saved, with its key, or the save\n\t * fails. A Save sent with an id that matches no row is refused before the handler runs.\n\t *\n\t * @example\n\t * ```ts\n\t * createStonecropPlugin({\n\t * actionHandlers: {\n\t * Order: {\n\t * async recalculateTotal({ pgClient, recordId }) {\n\t * const { rows } = await pgClient.query({\n\t * text: 'UPDATE \"order\" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',\n\t * values: [recordId],\n\t * })\n\t * return rows[0]\n\t * },\n\t * },\n\t * },\n\t * })\n\t * ```\n\t */\n\tactionHandlers?: Record<string, Record<string, ActionHandler>>\n\t/**\n\t * Row cap when nothing else names one: for `stonecropRecords` called without a `limit`, and for\n\t * a many-side link whose declaration has no `fetch.limit`. Defaults to 200; `null` removes it,\n\t * so an unqualified list returns the whole table and a link the whole relation.\n\t *\n\t * A truncated answer is always reported: `hasMore` for a list, `truncatedLinks` for a record.\n\t * A link cannot be paged, so a client that writes back a truncated link deletes the rows it was\n\t * never sent.\n\t */\n\tdefaultRecordLimit?: number | null\n}\n\n/**\n * Carries a reported failure out through a `throw`, purely so the transaction rolls back.\n *\n * `applyGuardedTransition` reports every failure as a return value, and a value returned from\n * inside `withTransaction` commits. This is the adapter between \"the action failed\" and \"undo it\"\n * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and\n * answers with the original envelope.\n */\nclass ActionRolledBack extends Error {\n\tconstructor(readonly outcome: { success: boolean; data: unknown; error: string | null }) {\n\t\tsuper(outcome.error ?? 'Action failed')\n\t\tthis.name = 'ActionRolledBack'\n\t}\n}\n\n/** One record a read is asked for: the arguments `stonecropRecord` takes. */\ninterface RecordReadSpec {\n\tdoctype: unknown\n\tid: unknown\n\toptions?: unknown\n}\n\n/** One record as `stonecropRecord` serves it. */\ninterface RecordReadResult {\n\tdata: Record<string, unknown> | null\n\tdoctype: string\n\tunknownLinks?: string[]\n\ttruncatedLinks?: string[]\n}\n\n/**\n * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can\n * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getColumnSelections`\n * omits its FK column by design — but the expansion needs the value to find the target. Aliasing\n * keeps that need from changing the payload: every alias is stripped before the record is returned.\n */\nconst LINK_FK_ALIAS = '__stonecropLinkFk_'\n\n/**\n * The column this adapter keeps a record's workflow state in.\n *\n * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,\n * the transition's write, and the data write that must refuse to touch it. A patch that could set\n * this column would let any client walk past `allowedStates` by writing the very value the guard\n * reads.\n */\nconst STATE_COLUMN = 'status'\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\t// Resolved once, for both read paths. `undefined` means \"not configured\" and `null` means\n\t// \"configured off\", which is a distinction `??` cannot make — and the two paths disagreeing\n\t// about it is exactly how a link came to be capped by a different number than a list.\n\tconst defaultRowLimit: number | null = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit\n\n\tconst schemaPlugin = 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 pgRegistry = (build as any).input?.pgRegistry as\n\t\t\t| { pgExecutors?: Record<string, PgExecutor>; pgCodecs?: Record<string, PgCodec> }\n\t\t\t| undefined\n\t\tconst executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.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\t\tconst columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables)\n\n\t\t// Schema build is the one point where both the registry and the plugin's options are in\n\t\t// hand, so it is where a stale registration can be caught before it silently no-ops.\n\t\tif (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers)\n\t\tassertReferencesResolve()\n\n\t\t/** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */\n\t\tconst readRecords = async (pgClient: PgClient, specs: readonly RecordReadSpec[]): Promise<RecordReadResult[]> => {\n\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t}\n\n\t\t\tconst results: RecordReadResult[] = Array.from({ length: specs.length })\n\n\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\tif (!meta) {\n\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Not `data: null` — that is the answer for a record that does not exist, and a\n\t\t\t\t// doctype nobody can look up is a misconfiguration, not an empty result.\n\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(doctype)\n\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t// Resolved once per doctype: how each link renders, and which foreign keys the\n\t\t\t\t// SELECT must carry for the expansion below to work at all.\n\t\t\t\t//\n\t\t\t\t// `resolveLinkRenderMode` needs the linked field's own component, so the fields\n\t\t\t\t// are indexed by name — flattened, because a link's field may sit inside a\n\t\t\t\t// fieldset and `getColumnSelections` already descends to select it.\n\t\t\t\tconst fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]))\n\t\t\t\tconst linkFkAliases: Array<{ fieldname: string; alias: string }> = []\n\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links ?? {})) {\n\t\t\t\t\t// Many-side links find their rows by a column on the *target*; only a one-side\n\t\t\t\t\t// link reads a foreign key off this row.\n\t\t\t\t\tif (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') continue\n\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t// An inline link keeps its FK as a scalar, so `getColumnSelections` already selected\n\t\t\t\t\t// it under its own name and no alias is needed.\n\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\t\t\t\t\tlinkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` })\n\t\t\t\t}\n\t\t\t\tconst select = columns.select(meta.name, [\n\t\t\t\t\t...getColumnSelections(meta),\n\t\t\t\t\t...linkFkAliases.map(({ fieldname, alias }) => ({ column: camelToSnake(fieldname), alias })),\n\t\t\t\t])\n\n\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\tvalues: [ids],\n\t\t\t\t})\n\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t// A declared key the database does not actually enforce as unique collapses several\n\t\t\t\t// rows into that Map, and it keeps whichever came last — one arbitrary record,\n\t\t\t\t// returned as though it were *the* record, with nothing to say so. Refuse instead.\n\t\t\t\t//\n\t\t\t\t// This is exact rather than a proxy for the problem: `ANY` matches each requested id\n\t\t\t\t// once, so a shortfall here means two distinct rows genuinely share a key value. A\n\t\t\t\t// `pg_index` check would instead ask whether a unique constraint exists, which is the\n\t\t\t\t// cause rather than the harm — and would flag a column that is unique in practice but\n\t\t\t\t// unconstrained, which is a real and common shape.\n\t\t\t\tif (rows.length !== rowByPk.size) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Doctype \"${doctype}\" declares \"${pkMeta.fieldname}\" as its identity, but that column ` +\n\t\t\t\t\t\t\t`is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +\n\t\t\t\t\t\t\t`matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +\n\t\t\t\t\t\t\t`Declare a field that uniquely identifies a record, or add a unique constraint.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Collected across the batch so the display lookup runs once for all of them.\n\t\t\t\t// Called per row inside this loop it issued one query per record per link field,\n\t\t\t\t// which is the N+1 this batched loader exists to avoid — and silently, since the\n\t\t\t\t// enriched rows come out identical either way.\n\t\t\t\tconst enrichedRows: Record<string, unknown>[] = []\n\n\t\t\t\tfor (const i of indices) {\n\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\tenrichedRows.push(rowData)\n\t\t\t\t\t// Per record, not per doctype: two records of one doctype can differ in whether\n\t\t\t\t\t// a relation overflowed, and a shared list would report the wrong one truncated.\n\t\t\t\t\tconst truncatedLinks: string[] = []\n\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null\n\n\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t// The payload key is the *resolved* fieldname, not the map key: the client\n\t\t\t\t\t\t\t// binds a link to the field named `link.fieldname ?? key` and reads the\n\t\t\t\t\t\t\t// nested data off that field, so writing under the bare key put the result\n\t\t\t\t\t\t\t// somewhere nothing looks whenever a declaration named its own `fieldname`.\n\t\t\t\t\t\t\t// Identical for every declaration that omits `fieldname`, which is all of them\n\t\t\t\t\t\t\t// in this repo — hence latent until now.\n\t\t\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t// Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only\n\t\t\t\t\t\t\t// `SyncFetch` carries a `limit` — and the server default used to hang off its\n\t\t\t\t\t\t\t// `else`, so declaring the method a many-side link already defaults to removed\n\t\t\t\t\t\t\t// the cap entirely. \"Did the author write a limit?\" and \"did the author write\n\t\t\t\t\t\t\t// the word sync?\" are now asked separately.\n\t\t\t\t\t\t\tconst declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined\n\t\t\t\t\t\t\tconst effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined\n\n\t\t\t\t\t\t\t// The one gate. It used to be followed by a second test that re-asked the\n\t\t\t\t\t\t\t// same question using only `includeSet` — `null` for the boolean form — so\n\t\t\t\t\t\t\t// `includeNested: true` admitted every link here and then silently dropped\n\t\t\t\t\t\t\t// each non-`sync` one, handing back a partial record with no way to tell.\n\t\t\t\t\t\t\t// That test was redundant wherever it was correct: with a name list this gate\n\t\t\t\t\t\t\t// has already required membership, and without one it has already required\n\t\t\t\t\t\t\t// `sync`, so it could only ever fire in the boolean case it got wrong.\n\t\t\t\t\t\t\tconst shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\tif (handler) {\n\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// 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\trowData[fieldname] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// `resolveLinkRenderMode` is the single definition of whether a link expands,\n\t\t\t\t\t\t\t// and this loop was the one caller that never asked it. An `inline` link is a\n\t\t\t\t\t\t\t// picker: the field holds its own id and the client resolves display text\n\t\t\t\t\t\t\t// separately, so expanding it here overwrote that id with the whole target\n\t\t\t\t\t\t\t// record and left the picker with an object it cannot render.\n\t\t\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\n\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\tconst targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta))\n\n\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t// In the order the link names, so rows that keep their own position read in\n\t\t\t\t\t\t\t\t// it; `truncatedLinks` says the tail was cut, and the order says which tail.\n\t\t\t\t\t\t\t\tsql += orderClause(targetMeta, link.orderBy, targetSelect.table)\n\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t// One row more than the cap, same probe the list path uses: its presence\n\t\t\t\t\t\t\t\t\t// is the whole truncation answer and costs no second query.\n\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t}\n\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// 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\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\t// A truncated relation that says nothing is how a read-modify-write deletes\n\t\t\t\t\t\t\t\t// the tail: the client cannot tell 50 rows from all of them, so it writes\n\t\t\t\t\t\t\t\t// back what it was given. Reported for every source of truncation, the\n\t\t\t\t\t\t\t\t// author's `fetch.limit` included — that one is just as silent.\n\t\t\t\t\t\t\t\tif (effectiveLimit != null && linked.length > effectiveLimit) {\n\t\t\t\t\t\t\t\t\ttruncatedLinks.push(fieldname)\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read from the reserved alias, never the fieldname: an expanding link's FK\n\t\t\t\t\t\t\t\t// column is deliberately absent from `getColumnSelections`, so the plain read found\n\t\t\t\t\t\t\t\t// `undefined` on every record and answered `null` — a relation that looked\n\t\t\t\t\t\t\t\t// permanently empty rather than one nobody had asked the right question for.\n\t\t\t\t\t\t\t\tconst fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`]\n\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = null\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// `continue` here would drop the link from the payload, which reads to the\n\t\t\t\t\t\t\t\t// client as \"this record has no such relation\" rather than \"its target\n\t\t\t\t\t\t\t\t// cannot be identified\".\n\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name)\n\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\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// 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\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\trowData[fieldname] = linked[0] ?? null\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The aliases are a read channel for this loop, not part of the record. Stripped\n\t\t\t\t\t// unconditionally so a link that was never expanded cannot leak its raw FK into a\n\t\t\t\t\t// payload that has otherwise always described that relation as a nested object.\n\t\t\t\t\tfor (const { alias } of linkFkAliases) delete rowData[alias]\n\n\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\ttruncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// After the expansion loop, not before it: a link that expanded has replaced its\n\t\t\t\t// scalar FK with an object, and enrichment skips those. Running first stamped a\n\t\t\t\t// display value beside a relation that no longer had an id to display.\n\t\t\t\t//\n\t\t\t\t// Sequential per doctype group because `pgClient` is one checked-out connection,\n\t\t\t\t// so awaiting these together would only queue them inside the driver.\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop\n\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql)\n\t\t\t}\n\n\t\t\treturn results\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\treadRecords\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, $includeTotal }: 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\tincludeTotal: $includeTotal,\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\t// An unknown doctype answers \"no records\" rather than erroring, so a caller\n\t\t\t\t\t\t\t\t\t\t\t\t// who asked for a total gets 0. Returning null here would make null mean\n\t\t\t\t\t\t\t\t\t\t\t\t// two things — \"you did not ask\" and \"I could not say\" — and a client\n\t\t\t\t\t\t\t\t\t\t\t\t// cannot tell those apart.\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null }\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 select = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection). Built once for\n\t\t\t\t\t\t\t\t\t\t\t// the page and its total, which must count the rows the page is drawn from.\n\t\t\t\t\t\t\t\t\t\t\tconst filterValues: unknown[] = []\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\tfilterValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst column = camelToSnake(field)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`\"${column}\" = ${columns.bind(meta.name, column, `$${filterValues.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}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = [...filterValues]\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\t// A page is only meaningful against a fixed order, and LIMIT/OFFSET without one\n\t\t\t\t\t\t\t\t\t\t\t// is two independent scans of heap order — an UPDATE between them moves that row\n\t\t\t\t\t\t\t\t\t\t\t// to the tail, so the row it displaced is never returned and nothing in the\n\t\t\t\t\t\t\t\t\t\t\t// payload says a record was skipped. The identity makes the order total, which is\n\t\t\t\t\t\t\t\t\t\t\t// what makes page 2 start exactly where page 1 stopped.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null && typeof spec.orderBy !== 'string') {\n\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}\n\t\t\t\t\t\t\t\t\t\t\tconst orderByClause = orderClause(\n\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\tspec.orderBy == null ? undefined : readListOrderBy(spec.orderBy),\n\t\t\t\t\t\t\t\t\t\t\t\tselect.table\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. A caller that names no limit gets the configured default rather\n\t\t\t\t\t\t\t\t\t\t\t// than the whole table: omission is how an unbounded scan used to happen, and the\n\t\t\t\t\t\t\t\t\t\t\t// only guard against it lived in the scaffold's fetch helper, which is neither the\n\t\t\t\t\t\t\t\t\t\t\t// right layer nor present in a host that wrote its own.\n\t\t\t\t\t\t\t\t\t\t\t// Grafast passes arguments through as loosely-typed runtime values, so narrow\n\t\t\t\t\t\t\t\t\t\t\t// before doing arithmetic on this — same reason orderBy is validated above.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null && typeof spec.limit !== 'number') {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid limit: expected number, got ${typeof spec.limit}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit: number | null = spec.limit ?? defaultRowLimit\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 (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// One more row than asked for. Its presence is the whole `hasMore` answer, and\n\t\t\t\t\t\t\t\t\t\t\t\t// it is discarded below — this is why knowing a list is truncated costs no\n\t\t\t\t\t\t\t\t\t\t\t\t// second query, where a COUNT(*) would be a full scan on every list read.\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(effectiveLimit + 1)\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 ${select.list} FROM ${select.table}${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\t\t\t\t\t\t\t\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t\t\t\t\t\t\t\t// The extra row requested above is a probe, not data. Its presence is what makes\n\t\t\t\t\t\t\t\t\t\t\t// a capped page distinguishable from a complete table; trim it before anything\n\t\t\t\t\t\t\t\t\t\t\t// downstream can mistake it for a record.\n\t\t\t\t\t\t\t\t\t\t\tconst hasMore = effectiveLimit != null && rows.length > effectiveLimit\n\t\t\t\t\t\t\t\t\t\t\tconst data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)]\n\n\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql)\n\n\t\t\t\t\t\t\t\t\t\t\t// Total matching the filters, independent of LIMIT/OFFSET, and opt-in.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Explicitly requested rather than inferred from whether `count` was selected:\n\t\t\t\t\t\t\t\t\t\t\t// this resolver is a Grafast plan step and receives only its arguments, never the\n\t\t\t\t\t\t\t\t\t\t\t// selection set, and making the plan vary by selection is what Grafast optimises\n\t\t\t\t\t\t\t\t\t\t\t// against. An argument also puts the cost in the query the client wrote.\n\t\t\t\t\t\t\t\t\t\t\tlet count: number | null = null\n\t\t\t\t\t\t\t\t\t\t\tif (spec.includeTotal === true) {\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)}${whereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: filterValues,\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, doctype, hasMore, 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 table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Resolved lazily: only a state read or write needs the key column. A\n\t\t\t\t\t\t\t\t\t// record-less command reaches its handler on a doctype that declares no\n\t\t\t\t\t\t\t\t\t// primary key, which an eager check would refuse for no reason.\n\t\t\t\t\t\t\t\t\tconst pkColumn = () => {\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) throw unresolvableIdentityError(String(spec.doctype))\n\t\t\t\t\t\t\t\t\t\treturn camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t}\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 rawArgs = (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\tdata?: Record<string, unknown>\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\t// An inline link arrives as `{ id, displayText }`; a column takes the id alone.\n\t\t\t\t\t\t\t\t\t// Reduced here so no client has to know what storage accepts, in the rows of\n\t\t\t\t\t\t\t\t\t// each declared relation too.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The whole envelope, not just `recordData` below — handlers read `ctx.args`.\n\t\t\t\t\t\t\t\t\t// Copied, not mutated: `spec.actionArgs` is the request's own value.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line oxc/no-map-spread\n\t\t\t\t\t\t\t\t\tconst argList = rawArgs.map(entry =>\n\t\t\t\t\t\t\t\t\t\tentry?.data\n\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...entry,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: unwrapInlineLinks(meta, entry.data, getMeta),\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: entry\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\t\t\t\t\t\t\t\t\tconst recordData = argList[0]?.data ?? {}\n\n\t\t\t\t\t\t\t\t\t// The database author's effect for this action, if one is registered. Keyed\n\t\t\t\t\t\t\t\t\t// by the doctype's canonical name so a slug-resolved lookup above cannot\n\t\t\t\t\t\t\t\t\t// silently miss it.\n\t\t\t\t\t\t\t\t\tconst handler = options.actionHandlers?.[meta.name]?.[String(spec.action)]\n\n\t\t\t\t\t\t\t\t\t// What a data write is allowed to set. Column identifiers come from the\n\t\t\t\t\t\t\t\t\t// doctype and never from the request — `args` is an opaque JSON scalar, so\n\t\t\t\t\t\t\t\t\t// every key in `data` is browser-supplied — which is what makes it safe to\n\t\t\t\t\t\t\t\t\t// build SQL from a patch at all.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The same derivation the read path uses, so what a record exposes is what a\n\t\t\t\t\t\t\t\t\t// record accepts. `status` is removed because state is the workflow's to\n\t\t\t\t\t\t\t\t\t// move, never the patch's. A column the database fills itself is refused in\n\t\t\t\t\t\t\t\t\t// `partitionPatch`, which asks the table only when there is a row to write:\n\t\t\t\t\t\t\t\t\t// this map is built for every action, including one on a doctype with no table.\n\t\t\t\t\t\t\t\t\tconst writable = new Map(\n\t\t\t\t\t\t\t\t\t\tcolumnBackedFields(meta.fields)\n\t\t\t\t\t\t\t\t\t\t\t.filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)\n\t\t\t\t\t\t\t\t\t\t\t.map(f => [f.fieldname, f] as const)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Whether this doctype has a workflow state to read at all. Derived from the\n\t\t\t\t\t\t\t\t\t// same declarations, so the guard cannot look for a column the doctype's own\n\t\t\t\t\t\t\t\t\t// API surface does not describe.\n\t\t\t\t\t\t\t\t\tconst declaresState = columnBackedFields(meta.fields).some(\n\t\t\t\t\t\t\t\t\t\tf => camelToSnake(f.fieldname) === STATE_COLUMN\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Reported on the result rather than logged: a dropped key is data the user\n\t\t\t\t\t\t\t\t\t// believes was saved, which is the same data-loss signal `truncatedLinks`\n\t\t\t\t\t\t\t\t\t// carries for a truncated read.\n\t\t\t\t\t\t\t\t\tconst droppedFields: string[] = []\n\t\t\t\t\t\t\t\t\tconst partitionPatch = (patch: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\t\t\tconst cols: string[] = []\n\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\t\t\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\t\t\t\t\t\t\tif (!writable.has(key) || !columns.writable(meta.name, camelToSnake(key))) {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\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\t\t\t\t\t\t\t\t\t\t\t// An expanding link reads back as a nested record while its column\n\t\t\t\t\t\t\t\t\t\t\t// holds a scalar foreign key, so a read-modify-write hands this loop\n\t\t\t\t\t\t\t\t\t\t\t// an object bound for a uuid column. The name resolving is not\n\t\t\t\t\t\t\t\t\t\t\t// enough; the shape has to match a column value too.\n\t\t\t\t\t\t\t\t\t\t\tif (value !== null && typeof value === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\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\t\t\t\t\t\t\t\t\t\t\tcols.push(camelToSnake(key))\n\t\t\t\t\t\t\t\t\t\t\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn { cols, values }\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// One transaction spans the guard read, the effect and the state write, so an\n\t\t\t\t\t\t\t\t\t// action either lands whole or not at all. `withTransaction` issues `begin` at\n\t\t\t\t\t\t\t\t\t// the top level and a `savepoint` if something upstream already opened one, so\n\t\t\t\t\t\t\t\t\t// nesting is safe rather than something callers must avoid.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// Every statement below runs on `tx`, not on the outer client. Work sent to the\n\t\t\t\t\t\t\t\t\t// outer client — or to a connection a handler opens itself — is outside this\n\t\t\t\t\t\t\t\t\t// transaction and would survive a rollback.\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await pgClient.withTransaction(async (tx: PgClient) => {\n\t\t\t\t\t\t\t\t\t\t\tconst outcome = await applyGuardedTransition(\n\t\t\t\t\t\t\t\t\t\t\t\tactionDef,\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\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// A save is filed under the record's key, so a doctype without one\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// cannot save, even a record not created yet.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true) pkColumn()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No id in the envelope means no record was targeted at all, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the same answer as a lookup that misses: `null`, not `undefined`.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Selecting `status` unconditionally made this read fail outright on\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// any table without that column — and a self-transition reaches here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// not to read a state but to learn whether the row exists, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// what decides create vs. update. So the projection follows the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// doctype: a doctype that declares no state field has none to read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and the honest answer for a row it finds is \"exists, no state\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (Measured: 24 of FAB's 35 guarded tables have no `status` column.)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst projection = declaresState ? `\"${STATE_COLUMN}\"` : `\"${pkColumn()}\"`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FOR UPDATE holds the row until this transaction ends, so a second\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// action on the same record waits rather than reading the same state\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and acting on it too. Without it the guard is a check-then-act\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// race: two concurrent approvals both read PENDING and both proceed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, string | null>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${projection} FROM ${table} WHERE \"${pkColumn()}\"::text = $1 FOR UPDATE`,\n\t\t\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\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (rows.length === 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// An id that was dispatched and matched nothing is a record that has\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// gone away since the client read it, and saving it as a create mints\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// a second row under a new identity while the client believes it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// updated the first: a lost update that reports success. Refused here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// before the adapter's write or a registered handler can run.\n\t\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\t// The dispatcher cannot make this call: it never receives the id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// deliberately, since identity is the backend's business. So the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// distinction its `readState` contract collapses is restored here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// where the id is in scope.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`${actionDef.label ?? spec.action} failed: record ${String(recordId)} no longer exists.`\n\t\t\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\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn null\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\tif (!declaresState) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0][STATE_COLUMN] ?? undefined\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\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"${STATE_COLUMN}\" = $1 WHERE \"${pkColumn()}\"::text = $2`,\n\t\t\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\t\t})\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\t// The upsert, and the write path for record data unless a handler is\n\t\t\t\t\t\t\t\t\t\t\t\t\t// registered for the Save. `exists` comes from the guard's own read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t// so no second lookup decides it.\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\t// Returns the same projection the read path selects, never\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `RETURNING *`: raw columns come back snake_case, and the client\n\t\t\t\t\t\t\t\t\t\t\t\t\t// resolves identity by the *declared fieldname*. A doctype keyed\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `itemId` would receive `item_id`, find no identity, and file a\n\t\t\t\t\t\t\t\t\t\t\t\t\t// created record nowhere — which is that exact bug, already once\n\t\t\t\t\t\t\t\t\t\t\t\t\t// shipped and patched downstream.\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteData: async (patch: Record<string, unknown>, exists: boolean) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { cols, values } = partitionPatch(patch)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst returning = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Creating is what the *absence* of an id means; `readState` has\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// already refused an id that matched no row.\n\t\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\t// No identity is minted here. A declared key present in the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// patch is a natural key the user filled in and passes\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// through the whitelist like any other column; absent, the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// column default supplies it. Either way the row states its\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// own identity back.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst text = cols.length\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? `INSERT INTO ${table} (${cols.map(c => `\"${c}\"`).join(', ')}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(', ')}) RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, { text, values })\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\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\t\t// Nothing writable survived the patch. `SET` with no assignments\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// is a syntax error, and reporting failure would be wrong — the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// record is fine, it just has no new data. Read it back so the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// client still gets the record, with `droppedFields` saying why\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// nothing changed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (cols.length === 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${returning.list} FROM ${table} WHERE \"${pkColumn()}\"::text = $1`,\n\t\t\t\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\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\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\t\tconst assignments = cols\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.map((c, i) => `\"${c}\" = ${columns.bind(meta.name, c, `$${i + 1}`)}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET ${assignments} WHERE \"${pkColumn()}\"::text = $${cols.length + 1} RETURNING ${returning.list}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [...values, String(recordId)],\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\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\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\trunEffect: handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (currentState: string | undefined) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thandler({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpgClient: tx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoctype: String(spec.doctype),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taction: String(spec.action),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trecordId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata: recordData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\targs: argList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentState,\n\t\t\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: undefined,\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\t// The patch a self-transition persists. This adapter never passed it, which\n\t\t\t\t\t\t\t\t\t\t\t\t// was moot while it had no `writeData` — nothing consumed it. Wiring the write\n\t\t\t\t\t\t\t\t\t\t\t\t// without this argument saves an empty record and reports success.\n\t\t\t\t\t\t\t\t\t\t\t\trecordData\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// `applyGuardedTransition` REPORTS failure, it does not throw — a refused\n\t\t\t\t\t\t\t\t\t\t\t// guard and a handler that blew up both come back as `{ success: false }`.\n\t\t\t\t\t\t\t\t\t\t\t// Returning that normally would commit the transaction, so a handler that\n\t\t\t\t\t\t\t\t\t\t\t// wrote three rows and then threw would keep all three. Throwing here is\n\t\t\t\t\t\t\t\t\t\t\t// what makes the rollback happen; the envelope is carried across so the\n\t\t\t\t\t\t\t\t\t\t\t// caller still gets `success: false` rather than a GraphQL error.\n\t\t\t\t\t\t\t\t\t\t\tif (!outcome.success) throw new ActionRolledBack(outcome)\n\n\t\t\t\t\t\t\t\t\t\t\t// The identity the reply states, read before enrichment below turns a key\n\t\t\t\t\t\t\t\t\t\t\t// that is also a link into `{ id, displayText }`, which no read can look up.\n\t\t\t\t\t\t\t\t\t\t\tconst pkField = getPkMeta(meta)?.fieldname\n\t\t\t\t\t\t\t\t\t\t\tconst repliedId: unknown =\n\t\t\t\t\t\t\t\t\t\t\t\tpkField !== undefined && outcome.data !== null && typeof outcome.data === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Reflect.get(outcome.data, pkField)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined\n\n\t\t\t\t\t\t\t\t\t\t\t// A record a write returns is a record, so it carries the links a read\n\t\t\t\t\t\t\t\t\t\t\t// resolves. Enriching one path and not the other changes a record's\n\t\t\t\t\t\t\t\t\t\t\t// shape depending on how the client came by it: a link rendered its\n\t\t\t\t\t\t\t\t\t\t\t// display text until the record was saved, and its raw id from then\n\t\t\t\t\t\t\t\t\t\t\t// until the next full fetch. Nothing fails — the field just goes wrong.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Runs inside the transaction so the lookup sees the row just written,\n\t\t\t\t\t\t\t\t\t\t\t// and only on success, since a rolled-back action returns no record.\n\t\t\t\t\t\t\t\t\t\t\t// A result that is not a record at all — an effect's `{ state }` — has\n\t\t\t\t\t\t\t\t\t\t\t// no field the doctype declares as an inline link, so it is untouched.\n\t\t\t\t\t\t\t\t\t\t\tif (outcome.success && outcome.data !== null && typeof outcome.data === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\t// A predicate rather than an assertion: an element that is not an object has\n\t\t\t\t\t\t\t\t\t\t\t\t// no field to enrich, so dropping it is the honest answer.\n\t\t\t\t\t\t\t\t\t\t\t\tconst written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t(row: unknown): row is Record<string, unknown> => row !== null && typeof row === 'object'\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\tawait enrichLinkDisplayFields(tx, meta, written, columns, debugSql)\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// The record as a read returns it, whoever wrote it: the client files this,\n\t\t\t\t\t\t\t\t\t\t\t// never `data`, which stays the handler's own. Keyed by the declared identity\n\t\t\t\t\t\t\t\t\t\t\t// the reply states when it states one, since an action may create or re-key\n\t\t\t\t\t\t\t\t\t\t\t// the record, and by the dispatched id otherwise.\n\t\t\t\t\t\t\t\t\t\t\tconst readId = repliedId ?? recordId\n\t\t\t\t\t\t\t\t\t\t\tconst record =\n\t\t\t\t\t\t\t\t\t\t\t\treadId == null\n\t\t\t\t\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t: ((await readRecords(tx, [{ doctype: meta.name, id: readId }]))[0]?.data ?? null)\n\n\t\t\t\t\t\t\t\t\t\t\t// A save with no record to file leaves the page on its draft, whose next save\n\t\t\t\t\t\t\t\t\t\t\t// creates a second record.\n\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true && record === null) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new ActionRolledBack({\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `${actionDef.label ?? spec.action} failed: the server did not say which record it saved.`,\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// Attached here rather than carried through `applyGuardedTransition`:\n\t\t\t\t\t\t\t\t\t\t\t// which keys a backend can store is a storage question, and the\n\t\t\t\t\t\t\t\t\t\t\t// dispatcher is deliberately storage-agnostic. A failed action wrote\n\t\t\t\t\t\t\t\t\t\t\t// nothing, so the list is only meaningful on success.\n\t\t\t\t\t\t\t\t\t\t\tconst reply = { ...outcome, record }\n\t\t\t\t\t\t\t\t\t\t\treturn droppedFields.length ? { ...reply, droppedFields } : reply\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\tif (err instanceof ActionRolledBack) return err.outcome\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\treturn {\n\t\t...schemaPlugin,\n\t\tgather: {\n\t\t\thooks: {\n\t\t\t\t// Marks a column Postgres generates as neither insertable nor updatable, as PostGraphile\n\t\t\t\t// itself marks an identity generated always. PostGraphile reads `attgenerated` only into\n\t\t\t\t// `hasDefault`, which a plain default shares, so without this the data write cannot tell\n\t\t\t\t// the two apart. On the adapter's plugin rather than the preset, so it holds wherever the\n\t\t\t\t// write runs.\n\t\t\t\tpgCodecs_attribute(_info, event) {\n\t\t\t\t\tconst { attgenerated } = event.pgAttribute\n\t\t\t\t\tif (attgenerated == null || attgenerated === '') return\n\t\t\t\t\tevent.attribute.extensions ??= {}\n\t\t\t\t\tevent.attribute.extensions.isInsertable = false\n\t\t\t\t\tevent.attribute.extensions.isUpdatable = false\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 * Derive column selections 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>): ColumnSelection[] {\n\tconst columns: ColumnSelection[] = []\n\tfor (const f of columnBackedFields(fields)) {\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// rule both sides of the wire share; 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\tcolumns.push({ column: camelToSnake(f.fieldname), alias: f.fieldname })\n\t}\n\treturn columns\n}\n\n/**\n * Derive the columns a record payload selects from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, and keeps\n * the fieldname as its alias 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 getColumnSelections(meta: DoctypeMeta): ColumnSelection[] {\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)\n}\n\n/**\n * Resolve the declared field this doctype's records are looked up by.\n *\n * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the\n * client's record keying name the same field — including the `id` fallback, whose absence here\n * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the\n * client and refused outright by this adapter, so every fetch answered `null` and looked exactly\n * like a record that does not exist.\n *\n * Returns `undefined` only when the resolved name is not a declared field — a doctype with no\n * `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields\n * only, so the row map would key on a column the SELECT never returned and every lookup would miss\n * silently. Callers must say so rather than answer `null`.\n *\n * Descends into fieldsets, because both halves of the question already do — `getColumnSelections` selects\n * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this\n * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose\n * SELECT carried its own key column had no identity to look that column up by.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\tconst fieldname = getRecordIdField(meta.fields)\n\treturn flattenFields(meta.fields).find((f): f is ValueField => f.kind === 'field' && f.fieldname === fieldname)\n}\n\n/**\n * The ORDER BY clause for reading a doctype's rows: the field `order` names, then the declared identity\n * to break ties, or the identity alone when nothing is named. Empty when the doctype declares no identity\n * and nothing is named.\n *\n * One definition for the list query and for a many-side link, which both cap what they read. A capped read\n * without a total order keeps an arbitrary set of rows, a different one whenever a row is updated and moves\n * in the heap, and only the identity is unique. Without an identity there is no stable key, and inventing\n * one would be a guess.\n *\n * Each term names its column through `table`, the statement's FROM. The select returns every column as text\n * under its fieldname, and a field named as its column (`position`, `id`, `created_at`) shares that name;\n * ORDER BY reads a bare name as the output column first, so it sorted that text and 10 came before 9.\n * Qualified, the name can only mean the column, compared as its own type.\n *\n * The named field must have a column (`columnBackedFields`): a computed field has none, and naming one would\n * reach Postgres as a missing column instead of being refused by name.\n */\nfunction orderClause(meta: DoctypeMeta, order: LinkDeclaration['orderBy'], table: string): string {\n\tconst terms: string[] = []\n\tif (order !== undefined) {\n\t\tif (!columnBackedFields(meta.fields).some(field => field.fieldname === order.fieldname)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown orderBy field: \"${order.fieldname}\" for doctype ${meta.name}; an order names a field with a database column`\n\t\t\t)\n\t\t}\n\t\tterms.push(`${table}.\"${camelToSnake(order.fieldname)}\" ${order.direction === 'desc' ? 'DESC' : 'ASC'}`)\n\t}\n\tconst pkMeta = getPkMeta(meta)\n\tif (pkMeta && pkMeta.fieldname !== order?.fieldname) {\n\t\tterms.push(`${table}.\"${camelToSnake(pkMeta.fieldname)}\" ASC`)\n\t}\n\treturn terms.length > 0 ? ` ORDER BY ${terms.join(', ')}` : ''\n}\n\n/**\n * The list query's `orderBy` argument, `FIELD_ASC` or `FIELD_DESC` with the direction in either case, read\n * as the order a link declares. The field is everything before the last underscore, so it may hold\n * underscores of its own.\n */\nfunction readListOrderBy(orderBy: string): NonNullable<LinkDeclaration['orderBy']> {\n\tconst lastUnder = orderBy.lastIndexOf('_')\n\tif (lastUnder <= 0) {\n\t\tthrow new Error(`Invalid orderBy format: \"${orderBy}\". Expected FIELD_ASC or FIELD_DESC`)\n\t}\n\tconst direction = orderBy.slice(lastUnder + 1).toLowerCase()\n\tif (direction !== 'asc' && direction !== 'desc') {\n\t\tthrow new Error(`Invalid orderBy direction: \"${direction.toUpperCase()}\". Must be ASC or DESC`)\n\t}\n\treturn { fieldname: orderBy.slice(0, lastUnder), direction }\n}\n\n/**\n * Assert that every registered action handler names a doctype and an action that exist.\n *\n * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler\n * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.\n * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it\n * has one, the missing effect is skipped and the state write still reports success. So renaming a\n * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.\n *\n * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a\n * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a\n * real doctype here and still never fires. It is reported as its own case rather than as \"unknown\n * doctype\", because the repair is different.\n *\n * Throws rather than warns: there is no legitimate reason to register a handler for an action that\n * does not exist, and the alternative is a silent half-executed workflow. Every offender is\n * collected so a consumer with several fixes them in one pass.\n */\nfunction assertActionHandlersResolve(actionHandlers: Record<string, Record<string, ActionHandler>>): void {\n\t// Nothing registered, nothing to check.\n\tconst registered = Object.entries(actionHandlers)\n\tif (registered.length === 0) return\n\n\t// An empty registry cannot tell \"this key is stale\" from \"doctypes have not loaded yet\" — a\n\t// host is free to build the schema before its loader runs. Warn on that ambiguity rather than\n\t// failing a boot that is merely early.\n\tif (getAllMeta().length === 0) {\n\t\t// oxlint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +\n\t\t\t\t'`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +\n\t\t\t\t'have stale handler keys reported.'\n\t\t)\n\t\treturn\n\t}\n\n\tconst orphans: string[] = []\n\tfor (const [doctypeKey, handlers] of registered) {\n\t\tconst meta = getMeta(doctypeKey)\n\t\tif (!meta) {\n\t\t\torphans.push(`\"${doctypeKey}\": no doctype by that name is registered`)\n\t\t\tcontinue\n\t\t}\n\t\tif (meta.name !== doctypeKey) {\n\t\t\torphans.push(\n\t\t\t\t`\"${doctypeKey}\": matches the doctype named \"${meta.name}\" by slug, but handlers are looked up by name — key it \"${meta.name}\"`\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst actions = meta.workflow?.actions ?? {}\n\t\tfor (const actionKey of Object.keys(handlers)) {\n\t\t\tif (!(actionKey in actions)) {\n\t\t\t\torphans.push(`\"${doctypeKey}.${actionKey}\": the doctype declares no action by that key`)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (orphans.length > 0) {\n\t\tthrow new Error(\n\t\t\t`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +\n\t\t\t\t`cannot be reached and would never run:\\n ${orphans.join('\\n ')}`\n\t\t)\n\t}\n}\n\n/**\n * Refuse a doctype set whose links or `inherits` name a doctype nobody registered, or whose links\n * bind or order by a field that cannot serve (see `validateReferences`).\n *\n * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed\n * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response\n * with no error. On the wire that is indistinguishable from \"this record has no such relation\", and\n * a typo in a target reads as a legitimately empty link forever.\n *\n * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not\n * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.\n *\n * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns\n * because a registered handler map is evidence the host meant to be checked; here there is no such\n * evidence, so warning would fire on every host that loads doctypes after building its schema —\n * and an advisory that fires on a correct setup is worse than none. An empty registry simply\n * reports nothing, because the loop has nothing to walk.\n */\nfunction assertReferencesResolve(): void {\n\tconst broken = validateReferences()\n\tif (broken.length === 0) return\n\n\tthrow new Error(\n\t\t`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +\n\t\t\t`cannot be resolved; each says what it breaks:\\n ` +\n\t\t\tbroken.map(e => `${e.path.join('.')}: ${e.message}`).join('\\n ')\n\t)\n}\n\n/**\n * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype\n * and both repairs. Shared so the three lookup sites report one diagnosis.\n */\nfunction unresolvableIdentityError(doctype: string): Error {\n\treturn new Error(\n\t\t`Doctype \"${doctype}\" has no identity field: it declares no field with \\`primaryKey: true\\` ` +\n\t\t\t`and no field named \\`id\\`. Declare one of the two — records cannot be fetched or acted on until then.`\n\t)\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 */\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 *\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\n/**\n * Stops Amber taking `id` for Relay's global object identifier.\n *\n * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called\n * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware\n * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`\n * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not\n * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that\n * node id and every read of it then fails on a missing column.\n *\n * Both inflectors must move together. Undoing the rename alone collides with the Relay field still\n * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called\n * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier\n * to `nodeId` keeps Relay working and is the name the schema converter already skips.\n *\n * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.\n */\nconst StonecropNaturalIdPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNaturalIdPlugin',\n\tversion: '0.0.0',\n\tafter: ['PgAttributesPlugin'],\n\tinflection: {\n\t\treplace: {\n\t\t\t// Move Relay's global identifier off `id`...\n\t\t\tnodeIdFieldName() {\n\t\t\t\treturn 'nodeId'\n\t\t\t},\n\n\t\t\t// ...so the real column can keep its own name.\n\t\t\t_attributeName(previous, options, details) {\n\t\t\t\t// `previous` is optional in the inflector signature because a replacement may be the first\n\t\t\t\t// implementation. It never is here — `after: ['PgAttributesPlugin']` guarantees Amber's runs\n\t\t\t\t// first — but the raw attribute name is the correct identity fallback.\n\t\t\t\tconst name = previous?.(details) ?? details.attributeName\n\t\t\t\tif (!details.skipRowId && name === 'row_id') {\n\t\t\t\t\tconst { codec, attributeName } = details\n\t\t\t\t\tconst baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName\n\t\t\t\t\tif (typeof baseName === 'string' && baseName.toLowerCase() === 'id' && !codec.isAnonymous) {\n\t\t\t\t\t\treturn 'id'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn name\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Exposes the many side of a foreign key the database declares as owning.\n *\n * PostGraphile registers both directions of every foreign key, but Amber gives the many side no\n * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s\n * inferred behavior is `[\"resource:select\", behavior]` and nothing more. So a parent type carries\n * no field for its children, and a doctype generated from that schema can never contain a child\n * table. Every one a consumer has is hand-authored.\n *\n * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.\n * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`\n * does not: an order references a party that outlives it. The two are otherwise the same shape, so\n * no amount of reading the relation itself can separate them — and turning the many side on for\n * *every* foreign key would make each referenced table look like somebody's child.\n *\n * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw\n * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.\n *\n * Connection only, deliberately. The converter recognises a Connection type through\n * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`\n * would add a second field per relation that generation then drops on the floor.\n *\n * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the\n * global default and take precedence, so `+manyRelation:resource:connection` there is overridden\n * for every relation — verified, it changes nothing, while `-connection +list` through the same\n * option visibly rewrites the Query fields.\n */\nconst StonecropOwnedRelationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropOwnedRelationsPlugin',\n\tversion: '0.0.0',\n\tgather: {\n\t\thooks: {\n\t\t\tpgRelations_relation(_info, event) {\n\t\t\t\tconst { relation, pgConstraint } = event\n\t\t\t\t// The hook fires once per direction of each constraint; only the backwards one has a\n\t\t\t\t// many side to expose. `confdeltype` is Postgres' own code: 'c' is CASCADE.\n\t\t\t\tif (!relation.isReferencee) return\n\t\t\t\tif (pgConstraint.confdeltype !== 'c') return\n\n\t\t\t\trelation.extensions ??= {}\n\t\t\t\trelation.extensions.tags ??= {}\n\t\t\t\trelation.extensions.tags.behavior = '+manyRelation:resource:connection'\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Offers no database function as a mutation.\n *\n * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard\n * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds\n * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.\n */\nconst StonecropNoFunctionMutationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNoFunctionMutationsPlugin',\n\tversion: '0.0.0',\n\tschema: {\n\t\tentityBehavior: {\n\t\t\tpgResource: {\n\t\t\t\toverride: {\n\t\t\t\t\t// After the hook that applies smart tags, so an app's `@behavior +mutationField` cannot undo it.\n\t\t\t\t\tafter: ['PgBasicsPlugin'],\n\t\t\t\t\tcallback(behavior) {\n\t\t\t\t\t\treturn [behavior, '-mutationField']\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n}\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. It turns off the mutations Amber generates, a create, update and delete for\n * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write\n * the API offers. 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: [\n\t\tStonecropNaturalIdPlugin,\n\t\tStonecropOwnedRelationsPlugin,\n\t\tStonecropNoFunctionMutationsPlugin,\n\t\t...(options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : []),\n\t],\n\t// Every write is an action, through `stonecropAction`, and Amber's create, update and delete for\n\t// each table would write past the doctype's guard. Disabled rather than set in\n\t// `schema.defaultBehavior`, which an app's own `defaultBehavior` replaces whole; `disablePlugins`\n\t// lists merge.\n\tdisablePlugins: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin'],\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 StonecropP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":["flattenFields","flattenFields","flattenFields"],"sources":["../src/fields.ts","../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/tables.ts","../src/columns.ts","../src/link-display.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import type { DoctypeField, ValueField } from '@stonecrop/schema'\nimport { flattenFields } from '@stonecrop/schema'\n\n// Re-exported so this module stays the one place the adapter asks about a doctype's fields, while\n// the definition itself lives in `@stonecrop/schema`. It moved there because `DoctypeMeta`'s own\n// validation needs the same descent, and the copy it had written instead scanned top level only —\n// so the load gate and the read path disagreed about what a doctype declares, which is exactly\n// what keeping one definition is for.\nexport { flattenFields }\n\n/**\n * The fields that have a database column of their own — the one definition of that question.\n *\n * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is\n * declared precisely to state it has no column, and a container (a table field) is a relation\n * rather than a value. Everything else names a column.\n *\n * This is deliberately **not** the same question as \"does this column belong in a record payload\".\n * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`\n * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the\n * two is how the read path came to drop the very column its expansion needed. Callers wanting the\n * payload projection filter this further by render mode; callers asking whether a column exists —\n * link validation, and the write path deciding what it may set — want it unfiltered.\n *\n * Extracted because the rule had grown three statements across two modules, one of them a comment\n * reading \"mirrors `collectColumns`\". A rule that has to be mirrored by hand is one edit away from\n * the read path and the validator disagreeing about what a doctype declares.\n */\nexport function columnBackedFields(fields: readonly DoctypeField[]): ValueField[] {\n\treturn flattenFields(fields).filter((f): f is ValueField => f.kind === 'field' && !f.computed)\n}\n","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\nimport { columnBackedFields, flattenFields } from '../fields'\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 doctype references — link targets, `inherits`, and each link's binding — against what\n * is loaded.\n *\n * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by\n * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as\n * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for\n * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.\n * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same\n * question the runtime asks.\n *\n * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers\n * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the\n * permissive direction.\n *\n * The **binding** checks are the same defect class as an unresolvable target, one step further in:\n * a link whose target resolves can still name no way to reach the rows, and the reader's answer for\n * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely\n * empty. Both halves of a declaration are `.optional()` in the schema because which one is required\n * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.\n *\n * Only what the runtime actually consults is required. A `backlink` naming a column the target\n * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;\n * the check exists for the silent cases, not to restate the database's own errors.\n *\n * A many-side link's `orderBy` is the exception, because the doctypes alone can decide it: it names\n * a field of the target, which must have a column. A misspelt one fails every read and save of this\n * doctype, and the read's error names the target rather than this link, so it is refused here, once.\n * The read keeps its own check for doctypes loaded after the schema is built. A one-side link reads\n * one row, so its `orderBy` would be ignored without a word, custom or not. A custom many-side link's\n * order is its handler's to apply, so it is not checked.\n *\n * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that\n * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only\n * meaningful after this module's own loaders have run.\n *\n * @internal\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 && getMeta(doctype.inherits) === undefined) {\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\tconst fields = flattenFields(doctype.fields)\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && getMeta(target) === undefined) {\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\tconst declared = new Set(fields.map(f => f.fieldname))\n\t\t\t// A foreign key is read from a column, so a link can only bind to a field that has one.\n\t\t\t// The rule itself lives in one place — see `columnBackedFields` — because the read path,\n\t\t\t// the write path and this check all have to answer it the same way.\n\t\t\tconst columnBacked = new Set(columnBackedFields(doctype.fields).map(f => f.fieldname))\n\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (getMeta(link.target) === undefined) {\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\n\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n\t\t\t\t// One row has no order, however it is fetched, so a one-side link's `orderBy` would be\n\t\t\t\t// ignored without a word.\n\t\t\t\tif (!isMany && link.orderBy) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'orderBy'],\n\t\t\t\t\t\tmessage: `Link \"${key}\" is ${link.cardinality} and reads one row, so its \\`orderBy\\` is never read. Remove it.`,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// A custom fetch strategy hands the whole read to its handler, which is given the\n\t\t\t\t// row and the declaration and finds the target however it likes, in the order it\n\t\t\t\t// likes. The runtime returns before consulting either binding below, or the order,\n\t\t\t\t// so requiring one would refuse a link that works.\n\t\t\t\tif (link.fetch?.method === 'custom') continue\n\n\t\t\t\t// The two cardinalities bind through different halves of the declaration, so the\n\t\t\t\t// check has to split the same way the reader does.\n\t\t\t\tif (isMany) {\n\t\t\t\t\t// Many-side: the target rows are found by a column on the *target* table, so\n\t\t\t\t\t// this doctype needs no field of its own — and the in-repo hosts disagree on\n\t\t\t\t\t// whether one exists, which is why only `backlink` can be required here.\n\t\t\t\t\tif (!link.backlink) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'backlink'],\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t`Link \"${key}\" is ${link.cardinality} but names no \\`backlink\\`, so the runtime cannot ` +\n\t\t\t\t\t\t\t\t`find the target rows and drops the link with no error. Name the field on \"${link.target}\" ` +\n\t\t\t\t\t\t\t\t`that points back to this doctype.`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tconst order = link.orderBy\n\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\tif (\n\t\t\t\t\t\torder &&\n\t\t\t\t\t\ttargetMeta &&\n\t\t\t\t\t\t!columnBackedFields(targetMeta.fields).some(f => f.fieldname === order.fieldname)\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst targetDeclares = flattenFields(targetMeta.fields).some(f => f.fieldname === order.fieldname)\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'orderBy', 'fieldname'],\n\t\t\t\t\t\t\tmessage: targetDeclares\n\t\t\t\t\t\t\t\t? `Link \"${key}\" orders its rows by \"${order.fieldname}\", which has no database column on ` +\n\t\t\t\t\t\t\t\t\t`\"${link.target}\" (it is computed, or a container rather than a value), so every read of ` +\n\t\t\t\t\t\t\t\t\t`this doctype fails. Order by a field with a column.`\n\t\t\t\t\t\t\t\t: `Link \"${key}\" orders its rows by \"${order.fieldname}\", which \"${link.target}\" does not ` +\n\t\t\t\t\t\t\t\t\t`declare, so every read of this doctype fails. Name a field of \"${link.target}\".`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// One-side: the foreign key is a column on *this* table, read as\n\t\t\t\t// `link.fieldname ?? key`. A name matching no declared field is not selected, so the\n\t\t\t\t// link resolves to null forever and reads as \"this record has no such relation\".\n\t\t\t\tconst fieldname = link.fieldname ?? key\n\t\t\t\tif (!columnBacked.has(fieldname)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\t// Point at whichever half actually carries the binding: the `fieldname`\n\t\t\t\t\t\t// property when it is set, otherwise the key itself. Naming `target` here\n\t\t\t\t\t\t// would send the reader to the one part that resolved correctly.\n\t\t\t\t\t\tpath: link.fieldname ? [doctype.name, 'links', key, 'fieldname'] : [doctype.name, 'links', key],\n\t\t\t\t\t\t// Two different repairs, so two different diagnoses: a name nothing declares\n\t\t\t\t\t\t// is a typo, while a name that resolves to a column-less field is a binding\n\t\t\t\t\t\t// pointed at the wrong one of several real fields.\n\t\t\t\t\t\tmessage: declared.has(fieldname)\n\t\t\t\t\t\t\t? `Link \"${key}\" binds to field \"${fieldname}\", which has no database column of its own — ` +\n\t\t\t\t\t\t\t\t`it is computed, or a container rather than a value — so there is no foreign key to read ` +\n\t\t\t\t\t\t\t\t`and the record read fails on the missing column. Bind the link to the field holding the ` +\n\t\t\t\t\t\t\t\t`foreign key.`\n\t\t\t\t\t\t\t: `Link \"${key}\" binds to field \"${fieldname}\", which this doctype does not declare, so it ` +\n\t\t\t\t\t\t\t\t`resolves to null with no error. Declare that field, or set \\`fieldname\\` to the field ` +\n\t\t\t\t\t\t\t\t`holding the foreign key. (A link's key is its fieldname unless \\`fieldname\\` overrides it.)`,\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 * The storage calls `applyGuardedTransition` makes. Each backend supplies its own.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/**\n\t * Read the record's workflow state: its state, `undefined` when it exists with no state, or\n\t * `null` when there is no such record. Return `null`, not `undefined`, for a missing record, or\n\t * an action on it can report success while writing nothing.\n\t *\n\t * For a self-transition sent with an id that matches no record, throw instead: the record was\n\t * deleted since it was read, and creating it would report a lost update as a success.\n\t */\n\treadState: () => Promise<string | null | undefined>\n\t/** Write the record's new workflow state. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Save a self-transition's field data and return the whole record, including its key. When\n\t * `exists` is false, create the record: take its key from `patch` for a natural-keyed doctype,\n\t * or mint one. An empty return for a create fails the action.\n\t *\n\t * Optional: without it, a self-transition fails unless `runEffect` is supplied. Never called\n\t * when `runEffect` is supplied.\n\t */\n\twriteData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>\n\t/**\n\t * Run the server-side handler registered for this action, once it passes its `allowedStates`\n\t * check (a self-transition creating a record skips that check), and before the state is\n\t * written. A stateless command fails without one.\n\t *\n\t * Its return becomes the result's `data`. On a self-transition it is the whole save, on a record\n\t * not created yet too, and must return the record it saved or the action fails. Throwing fails\n\t * the action; undoing what it wrote is the backend's job (the Postgres adapter runs each action\n\t * in a transaction).\n\t *\n\t * @param currentState - The state `readState` returned (`''` for a record with no state), or\n\t * `undefined` when it was not read or the record does not exist yet\n\t */\n\trunEffect?: (currentState: string | undefined) => Promise<unknown>\n}\n\n/**\n * Run a workflow action on the server: check `allowedStates`, then apply the action through `io`.\n *\n * - A **transition** (`nextState`) runs `io.runEffect` if supplied, then writes the new state.\n *\n * - A **self-transition** (`selfTransition`, such as Save) saves the record's data and keeps its\n * state, through `io.runEffect` if supplied and `io.writeData` otherwise.\n *\n * - A **stateless command** (neither) runs `io.runEffect` and leaves the state alone.\n *\n * - Anything else fails without touching the backend.\n *\n * On a record that does not exist yet, a self-transition creates it without checking\n * `allowedStates`, a command with no `allowedStates` runs, and anything else fails: the actions\n * `isActionAllowedOnNewRecord` allows. On a saved record the check is the same rule the client's\n * `getAvailableTransitions` uses.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and `nextState` or `selfTransition`\n * @param io - The backend's storage calls\n * @param data - The record's field data, for a self-transition\n * @returns Whether the action succeeded, the record or state it produced, and any error\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\tconst label = actionDef.label ?? 'unknown'\n\tconst isSelfTransition = actionDef.selfTransition === true\n\tconst hasStateOutcome = isSelfTransition || actionDef.nextState != null\n\n\t// A throw is attributed to the action by name: the adapter's handler is code the doctype\n\t// author cannot see, so an anonymous failure would be undebuggable from either side.\n\tconst runEffect = async (effect: NonNullable<GuardedTransitionIO['runEffect']>, currentState: string | undefined) => {\n\t\ttry {\n\t\t\treturn { ran: true as const, result: await effect(currentState) }\n\t\t} catch (err) {\n\t\t\tconst error = `Action \"${label}\" failed: ${err instanceof Error ? err.message : String(err)}`\n\t\t\treturn { ran: false as const, failure: { success: false, data: null, error } }\n\t\t}\n\t}\n\n\t// A self-transition with an effect: the effect is the write, on a new record and a saved one\n\t// alike, and owes the record it saved, as `writeData` does.\n\tconst saveThroughEffect = async (\n\t\teffect: NonNullable<GuardedTransitionIO['runEffect']>,\n\t\tcurrentState: string | undefined\n\t) => {\n\t\tconst effectOutcome = await runEffect(effect, currentState)\n\t\tif (!effectOutcome.ran) return effectOutcome.failure\n\t\tconst record = effectOutcome.result\n\t\tif (record === null || typeof record !== 'object' || Array.isArray(record) || Object.keys(record).length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `${label} failed: the server did not return the saved record.`,\n\t\t\t}\n\t\t}\n\t\treturn { success: true, data: record, error: null }\n\t}\n\n\t// Nothing to apply and no effect registered — fail loudly WITHOUT touching the backend.\n\t// This is the honest report for both causes: an action authored with no outcome, and a\n\t// command whose server handler the adapter never registered.\n\tif (!hasStateOutcome && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`,\n\t\t}\n\t}\n\n\t// A self-transition exists to persist data; with no way at all to do that — no data write, no\n\t// create, no effect — reject before running anything rather than half-applying.\n\tif (isSelfTransition && !io.writeData && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" persists record data in place, which this backend does not support.`,\n\t\t}\n\t}\n\n\t// Read the authoritative state only when something actually consumes it: the guard, or a\n\t// state outcome that the caller's readState is paired with. A handler-only command on a\n\t// doctype with no `status` column must not be forced through a read it never uses.\n\tconst isGuarded = (actionDef.allowedStates?.length ?? 0) > 0\n\tlet currentState: string | undefined\n\tif (isGuarded || hasStateOutcome) {\n\t\tconst state = await io.readState()\n\t\t// A missing record is reported, never guarded around. Reaching the guard with a state of\n\t\t// `''` produced two wrong answers depending only on whether the action declared\n\t\t// `allowedStates`: a misleading \"not allowed from state: (unknown)\" when it did, and a\n\t\t// silent `{ success: true }` writing nothing when it did not.\n\t\tif (state === null) {\n\t\t\t// A self-transition against a record that is not there is a create — the same write,\n\t\t\t// against a row that does not exist yet. The guard is deliberately skipped:\n\t\t\t// `allowedStates` constrains movement between states, and a record being created is not\n\t\t\t// in one; its initial state is the backend's to set.\n\t\t\tif (isSelfTransition && io.runEffect) return saveThroughEffect(io.runEffect, undefined)\n\t\t\tif (isSelfTransition && io.writeData) {\n\t\t\t\tconst created = await io.writeData(data ?? {}, false)\n\t\t\t\t// A backend that only knows how to patch returns nothing here, having matched no\n\t\t\t\t// row. Reporting that as success is the exact bug the `null` answer above exists to\n\t\t\t\t// kill, so it must not come back through the create path.\n\t\t\t\tif (!created || Object.keys(created).length === 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: `Action \"${label}\" targets a record that does not exist, and the backend did not create it.`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { success: true, data: created, error: null }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" targets a record that does not exist — nothing was executed.`,\n\t\t\t}\n\t\t}\n\t\tcurrentState = state ?? ''\n\t}\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. The full updated\n\t// record is returned so a created record's identity is known. Never `writeData` after an\n\t// effect: the effect is the write, and a second one would put the form's values back over it.\n\tif (isSelfTransition) {\n\t\tif (io.runEffect) return saveThroughEffect(io.runEffect, currentState)\n\t\tconst record = await io.writeData?.(data ?? {}, true)\n\t\treturn { success: true, data: record ?? null, error: null }\n\t}\n\n\t// The effect runs after the guard and before any write, so a handler that rejects cannot\n\t// leave the record in the target state.\n\tlet effectResult: unknown\n\tif (io.runEffect) {\n\t\tconst effect = await runEffect(io.runEffect, currentState)\n\t\tif (!effect.ran) return effect.failure\n\t\teffectResult = effect.result\n\t}\n\n\t// The state is read above and written here as two calls, with any effect between them. A\n\t// backend must hold the record between the two, or two concurrent transitions can both pass\n\t// the guard; the Postgres adapter does, by reading with FOR UPDATE inside the action's\n\t// transaction.\n\tif (actionDef.nextState == null) {\n\t\t// A stateless command: the effect (guaranteed present by the top guard) is the whole\n\t\t// outcome. It must not move the record — that is the doctype's call, not the handler's.\n\t\treturn { success: true, data: effectResult ?? null, error: null }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\t// The freshest thing the backend produced wins: a handler that returned a record describes\n\t// the row better than the state alone, which is all a bare transition knows.\n\treturn {\n\t\tsuccess: true,\n\t\tdata: effectResult ?? { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { pascalToSnake } from '@stonecrop/schema'\n\n/** A table a doctype reads from, as named before quoting. `schema` is absent for an unqualified name. */\nexport interface TableRef {\n\tschema?: string\n\tname: string\n}\n\n/**\n * The table a doctype reads from: the `tables` override when the adapter supplies one, otherwise the\n * doctype name snake-cased.\n *\n * The one definition of that mapping. It lives in its own module rather than beside either caller\n * because the plugin imports the link-display enrichment, so the enrichment cannot import back —\n * and the copy it made instead was byte-identical, which is the state a mapping is in right before\n * one side learns about schema-qualified names and the other does not.\n *\n * A dotted override is read as `schema.table`, so a table in a non-default Postgres schema keeps\n * its schema instead of becoming one name containing a dot.\n */\nexport function resolveTable(name: string, tables?: Record<string, string>): TableRef {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn { schema: target.slice(0, dotIndex), name: target.slice(dotIndex + 1) }\n\t}\n\treturn { name: target }\n}\n\n/** The quoted SQL table a doctype reads from (see `resolveTable`). */\nexport function resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst table = resolveTable(name, tables)\n\treturn table.schema === undefined ? `\"${table.name}\"` : `\"${table.schema}\".\"${table.name}\"`\n}\n","import { LIST_TYPES, TYPES } from '@dataplan/pg'\nimport type { PgCodec, PgCodecAttribute, PgExecutor } from '@dataplan/pg'\nimport { sql } from 'postgraphile/pg-sql2'\nimport type { SQL } from 'postgraphile/pg-sql2'\nimport { Temporal } from 'temporal-polyfill'\n\nimport { resolveTable, resolveTableName } from './tables'\n\n/** A column to read, and the key its value comes back under. */\nexport interface ColumnSelection {\n\tcolumn: string\n\talias: string\n}\n\n/** One doctype's table, with a select list whose values read as PostGraphile reads them. */\nexport interface ColumnSelect {\n\t/** The quoted table. */\n\ttable: string\n\t/** Each column cast to text, under its alias: as PostGraphile casts it, but for the exceptions `createColumnReader` names. */\n\tlist: string\n\t/** Decodes every selected value in place with the codec PostGraphile decodes it with. */\n\tdecodeRows(rows: readonly Record<string, unknown>[]): void\n}\n\n/** Builds the select list for a doctype's columns, and the SQL that binds a value to one. */\nexport interface ColumnReader {\n\tselect(doctype: string, selections: readonly ColumnSelection[]): ColumnSelect\n\t/** `placeholder` as the value for `column`, cast where the column needs its value converted. */\n\tbind(doctype: string, column: string, placeholder: string): string\n\t/**\n\t * `value` encoded for `column` with the codec its read decodes it with, so a value a read served is\n\t * written back as the same value. One of the wrong shape is refused, never written as another value.\n\t */\n\tencode(doctype: string, column: string, value: unknown): EncodedValue\n\t/** Whether a write may set `column`: not one the database fills itself, which PostGraphile marks as neither insertable nor updatable. */\n\twritable(doctype: string, column: string): boolean\n}\n\n/** The value to bind for a column, or why the column cannot take the value it was sent (`must be a list`). */\nexport type EncodedValue = { value: unknown } | { refused: string }\n\n/** A domain's underlying type, through any domains stacked on it. */\nconst baseCodec = (codec: PgCodec): PgCodec => (codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec)\n\nconst DATE_TIME_TYPES = new Set<PgCodec>([TYPES.date, TYPES.timestamp, TYPES.timestamptz])\nconst GEOMETRIC_TYPES = new Set<PgCodec>([TYPES.point, TYPES.lseg, TYPES.box, TYPES.path, TYPES.polygon, TYPES.circle])\n\n/** Whether a type's value is read as an object: JSON, a composite, a range or a geometric type. */\nconst readsAsObject = (codec: PgCodec): boolean =>\n\tcodec === TYPES.json ||\n\tcodec === TYPES.jsonb ||\n\tBoolean(codec.attributes) ||\n\tBoolean(codec.rangeOfCodec) ||\n\tGEOMETRIC_TYPES.has(codec)\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\tvalue !== null && typeof value === 'object' && !Array.isArray(value)\n\nconst hasExactly = (value: Record<string, unknown>, keys: readonly string[]): boolean =>\n\tObject.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key))\n\n/** Whether `value` has the shape a read of `codec` serves, so that encoding it cannot write some other value. */\nconst fitsShape = (codec: PgCodec, value: unknown): boolean => {\n\tif (value === null) return true\n\tconst base = baseCodec(codec)\n\tif (base === TYPES.json || base === TYPES.jsonb) return true\n\tconst { arrayOfCodec, rangeOfCodec, attributes } = base\n\tif (arrayOfCodec) return Array.isArray(value) && value.every(entry => fitsShape(arrayOfCodec, entry))\n\tif (rangeOfCodec) {\n\t\tconst fitsBound = (bound: unknown) =>\n\t\t\tbound === null ||\n\t\t\t(isRecord(bound) &&\n\t\t\t\thasExactly(bound, ['value', 'inclusive']) &&\n\t\t\t\ttypeof bound.inclusive === 'boolean' &&\n\t\t\t\tbound.value !== null &&\n\t\t\t\tfitsShape(rangeOfCodec, bound.value))\n\t\treturn isRecord(value) && hasExactly(value, ['start', 'end']) && fitsBound(value.start) && fitsBound(value.end)\n\t}\n\tif (attributes) {\n\t\treturn (\n\t\t\tisRecord(value) &&\n\t\t\thasExactly(value, Object.keys(attributes)) &&\n\t\t\tObject.entries(attributes).every(([name, attribute]) => fitsShape(attribute.codec, value[name]))\n\t\t)\n\t}\n\treturn GEOMETRIC_TYPES.has(base) ? isRecord(value) : typeof value !== 'object'\n}\n\nconst fields = (composite: PgCodec): string => Object.keys(composite.attributes ?? {}).join(', ')\n\n/** The shape a read of `codec` serves, as a refusal names it. */\nconst shapeOf = (codec: PgCodec): string => {\n\tconst base = baseCodec(codec)\n\tif (base.arrayOfCodec) {\n\t\tconst element = baseCodec(base.arrayOfCodec)\n\t\tif (element.rangeOfCodec) return 'a list of ranges, each with a start and an end'\n\t\tif (element.attributes) return `a list of objects, each with exactly the fields ${fields(element)}`\n\t\treturn readsAsObject(element) ? 'a list' : 'a list of single values'\n\t}\n\tif (base.rangeOfCodec) return 'a range with a start and an end'\n\tif (base.attributes) return `an object with exactly the fields ${fields(base)}`\n\treturn GEOMETRIC_TYPES.has(base) ? 'an object' : 'a single value, not an object'\n}\n\n/** The cast for one date or time range, or `undefined` for any other type. */\nconst dateRangeCast = (codec: PgCodec): ((range: SQL) => SQL) | undefined => {\n\tconst bound = baseCodec(codec).rangeOfCodec\n\tconst castFromPg = bound && DATE_TIME_TYPES.has(baseCodec(bound)) ? baseCodec(bound).castFromPg : undefined\n\tif (!castFromPg) return undefined\n\tconst edge = (fragment: SQL) =>\n\t\tsql`case when isfinite(${fragment}) then ${castFromPg(fragment)} else ${fragment}::text end`\n\treturn range =>\n\t\tsql`case when ${range} is null then null else json_build_array(lower_inc(${range}), ${edge(sql`lower(${range})`)}, ${edge(sql`upper(${range})`)}, upper_inc(${range}))::text end`\n}\n\n/**\n * The select of a date or time range, or a list of them, keeping an infinite bound as the text Postgres\n * writes for it (`-infinity`) and a NULL range as null. Not PostGraphile's own cast, which reads an\n * infinite bound as no bound and a NULL range as one with no bounds, so a save of the read would write\n * `[-infinity, …)` back as `(, …)`. Bounds stay zone-free.\n */\nconst dateRangeSelect = (codec: PgCodec, columnSql: SQL): SQL | undefined => {\n\tconst rangeCast = dateRangeCast(codec)\n\tif (rangeCast) return rangeCast(columnSql)\n\tconst element = baseCodec(codec).arrayOfCodec\n\tconst elementCast = element && dateRangeCast(element)\n\tif (!elementCast) return undefined\n\tconst range = sql.identifier(Symbol('range'))\n\treturn sql`case when ${columnSql} is null then null else array(select ${elementCast(range)} from unnest(${columnSql}) as ${range})::text end`\n}\n\n/**\n * Temporal writes a negative duration signed as a whole (`-P1DT1H`), which Postgres refuses; Postgres\n * reads the sign on each part (`P-1DT-1H`).\n */\nconst signEachPart = (duration: string): string =>\n\tduration.startsWith('-P') ? duration.slice(1).replace(/\\d+(?:\\.\\d+)?(?=[YMWDHS])/g, '-$&') : duration\n\n/** How a column whose values carry no zone is converted into the moments they name. */\ninterface MomentConversion {\n\t/** The type Postgres converts it to, through the database's zone. */\n\ttype: 'timestamptz' | 'timestamptz[]'\n\tcastSql: SQL\n\t/** Reads the converted value as PostGraphile reads that type. */\n\tcodec: PgCodec\n}\n\n/**\n * The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which\n * names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast\n * Postgres itself makes through the database's zone, so a value leaves as a moment and a moment\n * comes back to the same reading. Every other column needs none.\n *\n * Not PostGraphile's own text for it: that carries no zone, so a browser reads it in its own zone\n * and sends back UTC, and every save moved the stored time by the user's offset.\n */\nconst momentConversion = (codec: PgCodec): MomentConversion | undefined => {\n\tif (baseCodec(codec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz', castSql: sql`::timestamptz`, codec: TYPES.timestamptz }\n\t}\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz[]', castSql: sql`::timestamptz[]`, codec: LIST_TYPES.timestamptz }\n\t}\n\treturn undefined\n}\n\n/** An interval as PostGraphile's cast writes it, `to_char(…, 'YYYY_MM_DD_HH24_MI_SS.US')`, each part signed apart. */\nconst INTERVAL_TEXT = /^(-?\\d+)_(-?\\d+)_(-?\\d+)_(-?\\d+)_(-?\\d+)_(-?\\d+)\\.(-?\\d+)$/\n\n/**\n * An interval, as PostGraphile's cast writes it, read as an ISO 8601 duration (`P1DT2H30M`): the value\n * a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Postgres writes an ISO 8601\n * duration back natively.\n *\n * Parsed here, not by PostGraphile's codec, which reads a second and a half less (`-01.-500000`) as -1 s.\n *\n * Postgres signs each part apart, so it can hold \"a day less an hour\", which no ISO 8601 duration can.\n * Such an interval throws rather than being read as some other length.\n */\nconst isoDuration = (text: string, describe: () => string): string => {\n\tconst match = INTERVAL_TEXT.exec(text)\n\tif (!match) throw new Error(`${describe()} is an interval in a form this reader does not know.`)\n\tconst [years, months, days, hours, minutes, seconds, fraction] = match.slice(1).map(Number)\n\tconst microseconds = seconds * 1e6 + fraction\n\tconst parts = [years, months, days, hours, minutes, microseconds]\n\tif (parts.some(value => value > 0) && parts.some(value => value < 0)) {\n\t\tthrow new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`)\n\t}\n\treturn Temporal.Duration.from({\n\t\tyears,\n\t\tmonths,\n\t\tdays,\n\t\thours,\n\t\tminutes,\n\t\tseconds: Math.trunc(microseconds / 1e6),\n\t\tmilliseconds: Math.trunc((microseconds % 1e6) / 1e3),\n\t\tmicroseconds: microseconds % 1e3,\n\t}).toString()\n}\n\nconst readIntervalList = (text: string, describe: () => string): unknown =>\n\tLIST_TYPES.text\n\t\t.fromPg(text)\n\t\t.map((interval: string | null) => (interval === null ? null : isoDuration(interval, describe)))\n\n/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */\nconst intervalShape = (codec: PgCodec): 'one' | 'list' | undefined => {\n\tif (baseCodec(codec) === TYPES.interval) return 'one'\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.interval) return 'list'\n\treturn undefined\n}\n\n/**\n * Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each\n * value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is\n * `2026-01-01`. Three exceptions: a `timestamp`, or a list of them, served as the moment each names in\n * the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`); an `interval`, or\n * a list of them, served as an ISO 8601 duration (see `isoDuration`); and a date or time range, or a\n * list of them, keeping its infinite bounds and a NULL (see `dateRangeSelect`).\n *\n * Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,\n * which names another day or hour outside UTC, and a save writes that shifted value back. Not a\n * process-wide `setTypeParser` either, which changes every other `pg` query in the host.\n */\nexport function createColumnReader(\n\tcodecs: Readonly<Record<string, PgCodec>>,\n\texecutor: PgExecutor,\n\ttables?: Record<string, string>\n): ColumnReader {\n\tconst tableCodecsByName = new Map<string, PgCodec[]>()\n\tfor (const codec of Object.values(codecs)) {\n\t\tconst pg = codec.extensions?.pg\n\t\tif (!codec.attributes || !codec.extensions?.isTableLike || !pg || codec.executor !== executor) continue\n\t\ttableCodecsByName.set(pg.name, [...(tableCodecsByName.get(pg.name) ?? []), codec])\n\t}\n\n\tconst findTableCodec = (doctype: string): PgCodec => {\n\t\tconst table = resolveTable(doctype, tables)\n\t\tconst matches = (tableCodecsByName.get(table.name) ?? []).filter(\n\t\t\tcodec => table.schema === undefined || codec.extensions?.pg?.schemaName === table.schema\n\t\t)\n\t\tif (matches.length === 1) return matches[0]\n\t\tconst quoted = resolveTableName(doctype, tables)\n\t\tif (matches.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" reads ${quoted}, which PostGraphile has not introspected, so its columns ` +\n\t\t\t\t\t`cannot be read the way PostGraphile reads them. Add the table's schema to the pgService, ` +\n\t\t\t\t\t`or map the doctype in \\`tables\\` to a table PostGraphile knows.`\n\t\t\t)\n\t\t}\n\t\tconst schemas = matches.map(codec => codec.extensions?.pg?.schemaName).join(', ')\n\t\tthrow new Error(\n\t\t\t`Doctype \"${doctype}\" reads ${quoted}, a name PostGraphile knows in more than one schema ` +\n\t\t\t\t`(${schemas}). Map the doctype in \\`tables\\` to \"schema.table\".`\n\t\t)\n\t}\n\n\tconst findAttribute = (doctype: string, tableCodec: PgCodec, column: string): PgCodecAttribute => {\n\t\tconst attribute = tableCodec.attributes?.[column]\n\t\tif (!attribute) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" declares a field for column \"${column}\", which ${resolveTableName(doctype, tables)} does not have.`\n\t\t\t)\n\t\t}\n\t\treturn attribute\n\t}\n\n\treturn {\n\t\tselect(doctype, selections) {\n\t\t\tconst tableCodec = findTableCodec(doctype)\n\t\t\tconst table = resolveTableName(doctype, tables)\n\t\t\t// Keyed by alias, so a column selected twice under one key is decoded once, as `pg` keeps one.\n\t\t\tconst decoders = new Map<string, (value: string) => unknown>()\n\t\t\tconst list = selections\n\t\t\t\t.map(({ column, alias }) => {\n\t\t\t\t\tconst columnCodec = findAttribute(doctype, tableCodec, column).codec\n\t\t\t\t\tconst conversion = momentConversion(columnCodec)\n\t\t\t\t\tconst readCodec = conversion?.codec ?? columnCodec\n\t\t\t\t\tconst columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column)\n\t\t\t\t\tconst cast =\n\t\t\t\t\t\tdateRangeSelect(columnCodec, columnSql) ?? readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`\n\t\t\t\t\tconst compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`)\n\t\t\t\t\t// This list is spliced into SQL whose placeholders the caller numbers, so a cast carrying\n\t\t\t\t\t// its own `$1` would silently bind the caller's first value.\n\t\t\t\t\tif (compiled.values.length > 0) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The codec for ${table}.\"${column}\" casts with a bound value, which this adapter cannot select.`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst shape = intervalShape(columnCodec)\n\t\t\t\t\tconst describe = (text: string) => () => `\"${alias}\" from ${table} (${text})`\n\t\t\t\t\tdecoders.set(\n\t\t\t\t\t\talias,\n\t\t\t\t\t\tshape === 'one'\n\t\t\t\t\t\t\t? text => isoDuration(text, describe(text))\n\t\t\t\t\t\t\t: shape === 'list'\n\t\t\t\t\t\t\t\t? text => readIntervalList(text, describe(text))\n\t\t\t\t\t\t\t\t: readCodec.fromPg\n\t\t\t\t\t)\n\t\t\t\t\treturn compiled.text\n\t\t\t\t})\n\t\t\t\t.join(', ')\n\n\t\t\treturn {\n\t\t\t\ttable,\n\t\t\t\tlist,\n\t\t\t\tdecodeRows(rows) {\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tfor (const [alias, fromPg] of decoders) {\n\t\t\t\t\t\t\tconst value = row[alias]\n\t\t\t\t\t\t\tif (value === null) continue\n\t\t\t\t\t\t\t// The list casts every column to text, so anything else is a row this select did not\n\t\t\t\t\t\t\t// produce, or one decoded already.\n\t\t\t\t\t\t\tif (typeof value !== 'string') {\n\t\t\t\t\t\t\t\tthrow new Error(`\"${alias}\" from ${table} is ${typeof value}, not the text its select returns.`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow[alias] = fromPg(value)\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\n\t\tbind(doctype, column, placeholder) {\n\t\t\tconst conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec)\n\t\t\treturn conversion ? `${placeholder}::${conversion.type}` : placeholder\n\t\t},\n\n\t\tencode(doctype, column, value) {\n\t\t\t// SQL NULL; a parameter Postgres types from the column it is bound to needs no cast.\n\t\t\tif (value === null) return { value }\n\t\t\tconst columnCodec = findAttribute(doctype, findTableCodec(doctype), column).codec\n\t\t\tconst codec = baseCodec(columnCodec)\n\t\t\t// Its read is wrong (`{1,-1,0}` reads as two points at the origin), and Postgres refuses its encoding.\n\t\t\tif (codec === TYPES.line) return { refused: 'is a line, which cannot be saved' }\n\t\t\t// The code editor sends JSON as text, which Postgres reads as the value it names.\n\t\t\tif (codec === TYPES.json || codec === TYPES.jsonb) {\n\t\t\t\treturn { value: typeof value === 'string' ? value : codec.toPg(value) }\n\t\t\t}\n\t\t\tif (!fitsShape(codec, value)) return { refused: `must be ${shapeOf(codec)}` }\n\t\t\tif (codec.arrayOfCodec) {\n\t\t\t\t// As text elements Postgres reads as intervals, since the interval codec writes only its own object.\n\t\t\t\tif (baseCodec(codec.arrayOfCodec) === TYPES.interval && Array.isArray(value)) {\n\t\t\t\t\tconst durations = value.map((entry: unknown) => (typeof entry === 'string' ? signEachPart(entry) : entry))\n\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the text list codec writes a null element as NULL and any other as its text; its type names strings only\n\t\t\t\t\treturn { value: LIST_TYPES.text.toPg(durations as string[]) }\n\t\t\t\t}\n\t\t\t\t// A list of zone-free timestamps arrives as moments, bound through `timestamptz[]` (`bind`).\n\t\t\t\treturn { value: (momentConversion(columnCodec)?.codec ?? codec).toPg(value) }\n\t\t\t}\n\t\t\tif (codec === TYPES.interval && typeof value === 'string') return { value: signEachPart(value) }\n\t\t\t// A range, a composite or a geometric value, which the shape check has made an object.\n\t\t\treturn readsAsObject(codec) ? { value: codec.toPg(value) } : { value }\n\t\t},\n\n\t\twritable(doctype, column) {\n\t\t\tconst { extensions } = findAttribute(doctype, findTableCodec(doctype), column)\n\t\t\treturn extensions?.isInsertable !== false || extensions?.isUpdatable !== false\n\t\t},\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema'\nimport type { PgClient } from '@dataplan/pg'\n\nimport type { ColumnReader } from './columns'\nimport { getMeta } from './registry/doctypes'\n\ntype SqlQueryFn = (\n\tpgClient: PgClient,\n\tquery: { text: string; values?: unknown[] }\n) => Promise<{ rows: readonly Record<string, unknown>[] }>\n\ninterface LinkDisplaySpec {\n\tfieldname: string\n\tdisplayField: string\n\ttargetPkFieldname: string\n\ttargetDoctype: string\n}\n\n/**\n * Normalize a scalar SQL cell value to a non-empty string, or nothing.\n *\n * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key\n * in the result, and the display text stamped into the payload. Rejecting objects is what each\n * of those wants: an object FK is a link that was already expanded, and an object display column\n * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it\n * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.\n */\nfunction scalarText(value: unknown): string | undefined {\n\tif (value == null || typeof value === 'object') return undefined\n\tif (typeof value === 'string') return value === '' ? undefined : value\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn undefined\n}\n\nfunction collectLinkDisplaySpecs(meta: DoctypeMeta): LinkDisplaySpec[] {\n\tconst specs: LinkDisplaySpec[] = []\n\n\tfor (const field of flattenFields(meta.fields)) {\n\t\tif (field.kind !== 'field' || !field.doctype) continue\n\n\t\tconst targetMeta = getMeta(field.doctype)\n\t\tif (!targetMeta) continue\n\n\t\t// `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`\n\t\t// makes at the load gate, so a nomination that parsed is one this can build a SELECT from.\n\t\t// A hand-rolled scan here admitted `computed` fields, whose column does not exist.\n\t\tconst displayField = getDisplayField(targetMeta.fields, targetMeta.displayField)\n\t\tif (!displayField) continue\n\n\t\tspecs.push({\n\t\t\tfieldname: field.fieldname,\n\t\t\tdisplayField: displayField.fieldname,\n\t\t\ttargetPkFieldname: getRecordIdField(targetMeta.fields),\n\t\t\ttargetDoctype: targetMeta.name,\n\t\t})\n\t}\n\n\treturn specs\n}\n\n/**\n * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a\n * `displayField`. Expanded relations (object values) are skipped.\n *\n * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch\n * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the\n * loader exists to prevent, and does so invisibly, since the result is identical either way.\n */\nexport async function enrichLinkDisplayFields(\n\tpgClient: PgClient,\n\tmeta: DoctypeMeta,\n\trows: Record<string, unknown>[],\n\tcolumns: ColumnReader,\n\tdebugSql: SqlQueryFn\n): Promise<void> {\n\tconst specs = collectLinkDisplaySpecs(meta)\n\tif (specs.length === 0 || rows.length === 0) return\n\n\tawait Promise.all(\n\t\tspecs.map(async spec => {\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = scalarText(row[spec.fieldname])\n\t\t\t\tif (id !== undefined) ids.add(id)\n\t\t\t}\n\t\t\tif (ids.size === 0) return\n\n\t\t\tconst pkColumn = camelToSnake(spec.targetPkFieldname)\n\t\t\tconst select = columns.select(spec.targetDoctype, [\n\t\t\t\t{ column: pkColumn, alias: spec.targetPkFieldname },\n\t\t\t\t{ column: camelToSnake(spec.displayField), alias: spec.displayField },\n\t\t\t])\n\n\t\t\tconst { rows: displayRows } = await debugSql(pgClient, {\n\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\tvalues: [Array.from(ids)],\n\t\t\t})\n\t\t\tselect.decodeRows(displayRows)\n\n\t\t\tconst displayById = new Map<string, string>()\n\t\t\tfor (const displayRow of displayRows) {\n\t\t\t\tconst key = scalarText(displayRow[spec.targetPkFieldname])\n\t\t\t\tconst text = scalarText(displayRow[spec.displayField])\n\t\t\t\tif (key === undefined || text === undefined) continue\n\t\t\t\tdisplayById.set(key, text)\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst rawId = row[spec.fieldname]\n\t\t\t\tconst idKey = scalarText(rawId)\n\t\t\t\tif (idKey === undefined) continue\n\t\t\t\tconst displayText = displayById.get(idKey)\n\t\t\t\tif (displayText === undefined) continue\n\t\t\t\trow[spec.fieldname] = { id: rawId, displayText }\n\t\t\t}\n\t\t})\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\theight: 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\tparts: 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\tconfig: JSON\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\tdisplayField: 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\t\"\"\"\n\t\tFields whose linked rows were cut short by a row cap, so data holds a prefix of the\n\t\trelation rather than all of it. Null when nothing was truncated. A link cannot be paged,\n\t\tso a client that sees a name here must not write that relation back — the rows it never\n\t\treceived would be deleted.\n\t\t\"\"\"\n\t\ttruncatedLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\t\"\"\"\n\t\tWhether further records exist beyond this page. Always answered — it is read from the\n\t\tpage itself (one extra row is requested and discarded), so it costs no second query.\n\t\t\"\"\"\n\t\thasMore: Boolean!\n\t\t\"\"\"\n\t\tTotal matching the filters, ignoring limit/offset. Null unless the query asked for it\n\t\twith includeTotal, because counting is a full scan on most backends.\n\t\t\"\"\"\n\t\tcount: Int\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\t\"\"\"\n\t\tWhat the action's registered handler returned, verbatim, or the outcome the doctype declared.\n\t\t\"\"\"\n\t\tdata: JSON\n\t\terror: String\n\t\t\"\"\"\n\t\tThe record as stonecropRecord returns it after the action, whoever wrote it. The client stores\n\t\tthis, never data. Null when the action failed or targets no record.\n\t\t\"\"\"\n\t\trecord: JSON\n\t\t\"\"\"\n\t\tKeys the write discarded because the doctype declares no column for them, because the\n\t\tfield is the workflow state, which only a transition moves, because the database fills the\n\t\tcolumn itself, or because the value was a linked record rather than the link's key. Null\n\t\twhen everything sent was stored. The action still succeeded — this is what it did not\n\t\tkeep, and a client that reports an unqualified success without checking it tells the user\n\t\tdata was saved that was not.\n\t\t\"\"\"\n\t\tdroppedFields: [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\tincludeTotal: Boolean\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 { DoctypeField, DoctypeMeta, LinkDeclaration, ValueField, GetRecordOptions } from '@stonecrop/schema'\nimport { camelToSnake, getRecordIdField, resolveLinkRenderMode, unwrapInlineLinks } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgCodec, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { createColumnReader } from '../columns'\nimport type { ColumnSelection } from '../columns'\nimport { columnBackedFields, flattenFields } from '../fields'\nimport { enrichLinkDisplayFields } from '../link-display'\nimport { resolveTableName } from '../tables'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta, validateReferences } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Everything a server-side action handler is given when `stonecropAction` dispatches to it.\n *\n * A context object rather than positional parameters so the set can grow without breaking\n * registered handlers — the adapters that supply these live in consumer repositories.\n * @public\n */\nexport interface ActionHandlerContext {\n\t/**\n\t * The database client for this action, inside the action's transaction: throwing rolls back\n\t * everything the handler wrote, and returning commits it.\n\t *\n\t * Never run `BEGIN` or `COMMIT` on it, which would commit work the action may still reject (a\n\t * `SAVEPOINT` undoes part of your work), and never open another connection, whose work would\n\t * not roll back. Its rows carry snake_case column names: return camelCase field names, by\n\t * aliasing in SQL or with `snakeToCamel` from `@stonecrop/schema` (ADR 0004).\n\t */\n\tpgClient: PgClient\n\t/** The doctype the action was dispatched against, as the client sent it. */\n\tdoctype: string\n\t/** The action's key in `workflow.actions` — the same string the handler was registered under. */\n\taction: string\n\t/** The resolved doctype metadata, for field names, the primary key, and the workflow. */\n\tmeta: DoctypeMeta\n\t/** The record's key from the request. Absent for a record not created yet, and for a command on no record. */\n\trecordId?: string | number\n\t/**\n\t * The record field data the client sent (`args[0].data`).\n\t *\n\t * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has\n\t * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist\n\t * the fields the action is allowed to touch.\n\t */\n\tdata: Record<string, unknown>\n\t/** The full argument envelope, for the actions that need more than the first record. */\n\targs: unknown[]\n\t/** The state the guard read (`''` for a record with no state), or `undefined` when nothing required reading it or the record does not exist yet. */\n\tcurrentState?: string\n}\n\n/**\n * A server-side handler for one doctype action, registered in `actionHandlers`.\n *\n * Throwing fails the action and rolls back what it wrote. The return becomes the result's `data`,\n * so use camelCase field names (ADR 0007). The client stores the record read back afterwards, by\n * the doctype's key in this return or else by the request's id.\n * @public\n */\nexport type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>\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 `pascalToSnake(doctype.name)`, so\n\t * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a\n\t * PascalCase name: `camelToSnake('User')` is `_user`.)\n\t */\n\ttables?: Record<string, string>\n\t/**\n\t * Server-side handlers for workflow actions, keyed by the doctype's `name` (not its slug), then\n\t * the action's key. A handler runs only once the action passes its `allowedStates` check, which a\n\t * Save creating a record skips. A stateless command (no `nextState`, no `selfTransition`) fails\n\t * without one, and a transition's runs before the new state is written.\n\t *\n\t * A Save's (`selfTransition`) handler is the whole save: it runs on a record not created yet\n\t * too, with no `recordId`, and must return the record it saved, with its key, or the save\n\t * fails. A Save sent with an id that matches no row is refused before the handler runs.\n\t *\n\t * @example\n\t * ```ts\n\t * createStonecropPlugin({\n\t * actionHandlers: {\n\t * Order: {\n\t * async recalculateTotal({ pgClient, recordId }) {\n\t * const { rows } = await pgClient.query({\n\t * text: 'UPDATE \"order\" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',\n\t * values: [recordId],\n\t * })\n\t * return rows[0]\n\t * },\n\t * },\n\t * },\n\t * })\n\t * ```\n\t */\n\tactionHandlers?: Record<string, Record<string, ActionHandler>>\n\t/**\n\t * Row cap when nothing else names one: for `stonecropRecords` called without a `limit`, and for\n\t * a many-side link whose declaration has no `fetch.limit`. Defaults to 200; `null` removes it,\n\t * so an unqualified list returns the whole table and a link the whole relation.\n\t *\n\t * A truncated answer is always reported: `hasMore` for a list, `truncatedLinks` for a record.\n\t * A link cannot be paged, so a client that writes back a truncated link deletes the rows it was\n\t * never sent.\n\t */\n\tdefaultRecordLimit?: number | null\n}\n\n/**\n * Carries a reported failure out through a `throw`, purely so the transaction rolls back.\n *\n * `applyGuardedTransition` reports every failure as a return value, and a value returned from\n * inside `withTransaction` commits. This is the adapter between \"the action failed\" and \"undo it\"\n * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and\n * answers with the original envelope.\n */\nclass ActionRolledBack extends Error {\n\tconstructor(readonly outcome: { success: boolean; data: unknown; error: string | null }) {\n\t\tsuper(outcome.error ?? 'Action failed')\n\t\tthis.name = 'ActionRolledBack'\n\t}\n}\n\n/** One record a read is asked for: the arguments `stonecropRecord` takes. */\ninterface RecordReadSpec {\n\tdoctype: unknown\n\tid: unknown\n\toptions?: unknown\n}\n\n/** One record as `stonecropRecord` serves it. */\ninterface RecordReadResult {\n\tdata: Record<string, unknown> | null\n\tdoctype: string\n\tunknownLinks?: string[]\n\ttruncatedLinks?: string[]\n}\n\n/**\n * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can\n * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getColumnSelections`\n * omits its FK column by design — but the expansion needs the value to find the target. Aliasing\n * keeps that need from changing the payload: every alias is stripped before the record is returned.\n */\nconst LINK_FK_ALIAS = '__stonecropLinkFk_'\n\n/**\n * The column this adapter keeps a record's workflow state in.\n *\n * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,\n * the transition's write, and the data write that must refuse to touch it. A patch that could set\n * this column would let any client walk past `allowedStates` by writing the very value the guard\n * reads.\n */\nconst STATE_COLUMN = 'status'\n\n/** Whether a link finds its rows by a column on the target, rather than by a key on this record. */\nconst isManySide = (link: LinkDeclaration): boolean =>\n\tlink.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\n/**\n * The key column of each expanding one-side link, under its `LINK_FK_ALIAS` alias. A many-side link\n * finds its rows by a column on the target, and an inline link keeps its key as a scalar that\n * `getColumnSelections` already selects under its own name.\n */\nfunction linkKeySelections(meta: DoctypeMeta): Array<ColumnSelection & { fieldname: string }> {\n\tconst fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]))\n\treturn Object.entries(meta.links ?? {}).flatMap(([linkName, link]) => {\n\t\tconst fieldname = link.fieldname ?? linkName\n\t\tif (isManySide(link) || resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') return []\n\t\treturn [{ fieldname, column: camelToSnake(fieldname), alias: `${LINK_FK_ALIAS}${fieldname}` }]\n\t})\n}\n\n/**\n * Whether two values are the same JSON value: object keys in any order, list items in order, and no\n * coercion (`\"5\"` is not `5`).\n */\nconst sameJsonValue = (left: unknown, right: unknown): boolean => {\n\tif (Array.isArray(left) || Array.isArray(right)) {\n\t\treturn (\n\t\t\tArray.isArray(left) &&\n\t\t\tArray.isArray(right) &&\n\t\t\tleft.length === right.length &&\n\t\t\tleft.every((entry, index) => sameJsonValue(entry, right[index]))\n\t\t)\n\t}\n\tif (left !== null && typeof left === 'object' && right !== null && typeof right === 'object') {\n\t\tconst leftKeys = Object.keys(left)\n\t\treturn (\n\t\t\tleftKeys.length === Object.keys(right).length &&\n\t\t\tleftKeys.every(key => Object.hasOwn(right, key) && sameJsonValue(Reflect.get(left, key), Reflect.get(right, key)))\n\t\t)\n\t}\n\treturn left === right\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\t// Resolved once, for both read paths. `undefined` means \"not configured\" and `null` means\n\t// \"configured off\", which is a distinction `??` cannot make — and the two paths disagreeing\n\t// about it is exactly how a link came to be capped by a different number than a list.\n\tconst defaultRowLimit: number | null = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit\n\n\tconst schemaPlugin = 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 pgRegistry = (build as any).input?.pgRegistry as\n\t\t\t| { pgExecutors?: Record<string, PgExecutor>; pgCodecs?: Record<string, PgCodec> }\n\t\t\t| undefined\n\t\tconst executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.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\t\tconst columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables)\n\n\t\t// Schema build is the one point where both the registry and the plugin's options are in\n\t\t// hand, so it is where a stale registration can be caught before it silently no-ops.\n\t\tif (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers)\n\t\tassertReferencesResolve()\n\n\t\t/** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */\n\t\tconst readRecords = async (pgClient: PgClient, specs: readonly RecordReadSpec[]): Promise<RecordReadResult[]> => {\n\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t}\n\n\t\t\tconst results: RecordReadResult[] = Array.from({ length: specs.length })\n\n\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\tif (!meta) {\n\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Not `data: null` — that is the answer for a record that does not exist, and a\n\t\t\t\t// doctype nobody can look up is a misconfiguration, not an empty result.\n\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(doctype)\n\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t// Resolved once per doctype: how each link renders, and which foreign keys the\n\t\t\t\t// SELECT must carry for the expansion below to work at all.\n\t\t\t\t//\n\t\t\t\t// `resolveLinkRenderMode` needs the linked field's own component, so the fields\n\t\t\t\t// are indexed by name — flattened, because a link's field may sit inside a\n\t\t\t\t// fieldset and `getColumnSelections` already descends to select it.\n\t\t\t\tconst fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]))\n\t\t\t\tconst linkFkAliases = linkKeySelections(meta)\n\t\t\t\tconst select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases])\n\n\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\tvalues: [ids],\n\t\t\t\t})\n\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t// A declared key the database does not actually enforce as unique collapses several\n\t\t\t\t// rows into that Map, and it keeps whichever came last — one arbitrary record,\n\t\t\t\t// returned as though it were *the* record, with nothing to say so. Refuse instead.\n\t\t\t\t//\n\t\t\t\t// This is exact rather than a proxy for the problem: `ANY` matches each requested id\n\t\t\t\t// once, so a shortfall here means two distinct rows genuinely share a key value. A\n\t\t\t\t// `pg_index` check would instead ask whether a unique constraint exists, which is the\n\t\t\t\t// cause rather than the harm — and would flag a column that is unique in practice but\n\t\t\t\t// unconstrained, which is a real and common shape.\n\t\t\t\tif (rows.length !== rowByPk.size) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Doctype \"${doctype}\" declares \"${pkMeta.fieldname}\" as its identity, but that column ` +\n\t\t\t\t\t\t\t`is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +\n\t\t\t\t\t\t\t`matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +\n\t\t\t\t\t\t\t`Declare a field that uniquely identifies a record, or add a unique constraint.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Collected across the batch so the display lookup runs once for all of them.\n\t\t\t\t// Called per row inside this loop it issued one query per record per link field,\n\t\t\t\t// which is the N+1 this batched loader exists to avoid — and silently, since the\n\t\t\t\t// enriched rows come out identical either way.\n\t\t\t\tconst enrichedRows: Record<string, unknown>[] = []\n\n\t\t\t\tfor (const i of indices) {\n\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\tenrichedRows.push(rowData)\n\t\t\t\t\t// Per record, not per doctype: two records of one doctype can differ in whether\n\t\t\t\t\t// a relation overflowed, and a shared list would report the wrong one truncated.\n\t\t\t\t\tconst truncatedLinks: string[] = []\n\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null\n\n\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t// The payload key is the *resolved* fieldname, not the map key: the client\n\t\t\t\t\t\t\t// binds a link to the field named `link.fieldname ?? key` and reads the\n\t\t\t\t\t\t\t// nested data off that field, so writing under the bare key put the result\n\t\t\t\t\t\t\t// somewhere nothing looks whenever a declaration named its own `fieldname`.\n\t\t\t\t\t\t\t// Identical for every declaration that omits `fieldname`, which is all of them\n\t\t\t\t\t\t\t// in this repo — hence latent until now.\n\t\t\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\tconst isMany = isManySide(link)\n\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t// Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only\n\t\t\t\t\t\t\t// `SyncFetch` carries a `limit` — and the server default used to hang off its\n\t\t\t\t\t\t\t// `else`, so declaring the method a many-side link already defaults to removed\n\t\t\t\t\t\t\t// the cap entirely. \"Did the author write a limit?\" and \"did the author write\n\t\t\t\t\t\t\t// the word sync?\" are now asked separately.\n\t\t\t\t\t\t\tconst declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined\n\t\t\t\t\t\t\tconst effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined\n\n\t\t\t\t\t\t\t// The one gate. It used to be followed by a second test that re-asked the\n\t\t\t\t\t\t\t// same question using only `includeSet` — `null` for the boolean form — so\n\t\t\t\t\t\t\t// `includeNested: true` admitted every link here and then silently dropped\n\t\t\t\t\t\t\t// each non-`sync` one, handing back a partial record with no way to tell.\n\t\t\t\t\t\t\t// That test was redundant wherever it was correct: with a name list this gate\n\t\t\t\t\t\t\t// has already required membership, and without one it has already required\n\t\t\t\t\t\t\t// `sync`, so it could only ever fire in the boolean case it got wrong.\n\t\t\t\t\t\t\tconst shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\tif (handler) {\n\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// 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\trowData[fieldname] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// `resolveLinkRenderMode` is the single definition of whether a link expands,\n\t\t\t\t\t\t\t// and this loop was the one caller that never asked it. An `inline` link is a\n\t\t\t\t\t\t\t// picker: the field holds its own id and the client resolves display text\n\t\t\t\t\t\t\t// separately, so expanding it here overwrote that id with the whole target\n\t\t\t\t\t\t\t// record and left the picker with an object it cannot render.\n\t\t\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\n\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\tconst targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta))\n\n\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t// In the order the link names, so rows that keep their own position read in\n\t\t\t\t\t\t\t\t// it; `truncatedLinks` says the tail was cut, and the order says which tail.\n\t\t\t\t\t\t\t\tsql += orderClause(targetMeta, link.orderBy, targetSelect.table)\n\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t// One row more than the cap, same probe the list path uses: its presence\n\t\t\t\t\t\t\t\t\t// is the whole truncation answer and costs no second query.\n\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t}\n\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// 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\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\t// A truncated relation that says nothing is how a read-modify-write deletes\n\t\t\t\t\t\t\t\t// the tail: the client cannot tell 50 rows from all of them, so it writes\n\t\t\t\t\t\t\t\t// back what it was given. Reported for every source of truncation, the\n\t\t\t\t\t\t\t\t// author's `fetch.limit` included — that one is just as silent.\n\t\t\t\t\t\t\t\tif (effectiveLimit != null && linked.length > effectiveLimit) {\n\t\t\t\t\t\t\t\t\ttruncatedLinks.push(fieldname)\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read from the reserved alias, never the fieldname: an expanding link's FK\n\t\t\t\t\t\t\t\t// column is deliberately absent from `getColumnSelections`, so the plain read found\n\t\t\t\t\t\t\t\t// `undefined` on every record and answered `null` — a relation that looked\n\t\t\t\t\t\t\t\t// permanently empty rather than one nobody had asked the right question for.\n\t\t\t\t\t\t\t\tconst fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`]\n\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = null\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// `continue` here would drop the link from the payload, which reads to the\n\t\t\t\t\t\t\t\t// client as \"this record has no such relation\" rather than \"its target\n\t\t\t\t\t\t\t\t// cannot be identified\".\n\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name)\n\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\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// 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\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\trowData[fieldname] = linked[0] ?? null\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The aliases are a read channel for this loop, not part of the record. Stripped\n\t\t\t\t\t// unconditionally so a link that was never expanded cannot leak its raw FK into a\n\t\t\t\t\t// payload that has otherwise always described that relation as a nested object.\n\t\t\t\t\tfor (const { alias } of linkFkAliases) delete rowData[alias]\n\n\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\ttruncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// After the expansion loop, not before it: a link that expanded has replaced its\n\t\t\t\t// scalar FK with an object, and enrichment skips those. Running first stamped a\n\t\t\t\t// display value beside a relation that no longer had an id to display.\n\t\t\t\t//\n\t\t\t\t// Sequential per doctype group because `pgClient` is one checked-out connection,\n\t\t\t\t// so awaiting these together would only queue them inside the driver.\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop\n\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql)\n\t\t\t}\n\n\t\t\treturn results\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\treadRecords\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, $includeTotal }: 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\tincludeTotal: $includeTotal,\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\t// An unknown doctype answers \"no records\" rather than erroring, so a caller\n\t\t\t\t\t\t\t\t\t\t\t\t// who asked for a total gets 0. Returning null here would make null mean\n\t\t\t\t\t\t\t\t\t\t\t\t// two things — \"you did not ask\" and \"I could not say\" — and a client\n\t\t\t\t\t\t\t\t\t\t\t\t// cannot tell those apart.\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null }\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 select = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection). Built once for\n\t\t\t\t\t\t\t\t\t\t\t// the page and its total, which must count the rows the page is drawn from.\n\t\t\t\t\t\t\t\t\t\t\tconst filterValues: unknown[] = []\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\tfilterValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst column = camelToSnake(field)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`\"${column}\" = ${columns.bind(meta.name, column, `$${filterValues.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}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = [...filterValues]\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\t// A page is only meaningful against a fixed order, and LIMIT/OFFSET without one\n\t\t\t\t\t\t\t\t\t\t\t// is two independent scans of heap order — an UPDATE between them moves that row\n\t\t\t\t\t\t\t\t\t\t\t// to the tail, so the row it displaced is never returned and nothing in the\n\t\t\t\t\t\t\t\t\t\t\t// payload says a record was skipped. The identity makes the order total, which is\n\t\t\t\t\t\t\t\t\t\t\t// what makes page 2 start exactly where page 1 stopped.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null && typeof spec.orderBy !== 'string') {\n\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}\n\t\t\t\t\t\t\t\t\t\t\tconst orderByClause = orderClause(\n\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\tspec.orderBy == null ? undefined : readListOrderBy(spec.orderBy),\n\t\t\t\t\t\t\t\t\t\t\t\tselect.table\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. A caller that names no limit gets the configured default rather\n\t\t\t\t\t\t\t\t\t\t\t// than the whole table: omission is how an unbounded scan used to happen, and the\n\t\t\t\t\t\t\t\t\t\t\t// only guard against it lived in the scaffold's fetch helper, which is neither the\n\t\t\t\t\t\t\t\t\t\t\t// right layer nor present in a host that wrote its own.\n\t\t\t\t\t\t\t\t\t\t\t// Grafast passes arguments through as loosely-typed runtime values, so narrow\n\t\t\t\t\t\t\t\t\t\t\t// before doing arithmetic on this — same reason orderBy is validated above.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null && typeof spec.limit !== 'number') {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid limit: expected number, got ${typeof spec.limit}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit: number | null = spec.limit ?? defaultRowLimit\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 (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// One more row than asked for. Its presence is the whole `hasMore` answer, and\n\t\t\t\t\t\t\t\t\t\t\t\t// it is discarded below — this is why knowing a list is truncated costs no\n\t\t\t\t\t\t\t\t\t\t\t\t// second query, where a COUNT(*) would be a full scan on every list read.\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(effectiveLimit + 1)\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 ${select.list} FROM ${select.table}${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\t\t\t\t\t\t\t\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t\t\t\t\t\t\t\t// The extra row requested above is a probe, not data. Its presence is what makes\n\t\t\t\t\t\t\t\t\t\t\t// a capped page distinguishable from a complete table; trim it before anything\n\t\t\t\t\t\t\t\t\t\t\t// downstream can mistake it for a record.\n\t\t\t\t\t\t\t\t\t\t\tconst hasMore = effectiveLimit != null && rows.length > effectiveLimit\n\t\t\t\t\t\t\t\t\t\t\tconst data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)]\n\n\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql)\n\n\t\t\t\t\t\t\t\t\t\t\t// Total matching the filters, independent of LIMIT/OFFSET, and opt-in.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Explicitly requested rather than inferred from whether `count` was selected:\n\t\t\t\t\t\t\t\t\t\t\t// this resolver is a Grafast plan step and receives only its arguments, never the\n\t\t\t\t\t\t\t\t\t\t\t// selection set, and making the plan vary by selection is what Grafast optimises\n\t\t\t\t\t\t\t\t\t\t\t// against. An argument also puts the cost in the query the client wrote.\n\t\t\t\t\t\t\t\t\t\t\tlet count: number | null = null\n\t\t\t\t\t\t\t\t\t\t\tif (spec.includeTotal === true) {\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)}${whereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: filterValues,\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, doctype, hasMore, 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 table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Resolved lazily: only a state read or write needs the key column. A\n\t\t\t\t\t\t\t\t\t// record-less command reaches its handler on a doctype that declares no\n\t\t\t\t\t\t\t\t\t// primary key, which an eager check would refuse for no reason.\n\t\t\t\t\t\t\t\t\tconst pkColumn = () => {\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) throw unresolvableIdentityError(String(spec.doctype))\n\t\t\t\t\t\t\t\t\t\treturn camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t}\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 rawArgs = (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\tdata?: Record<string, unknown>\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\t// An inline link arrives as `{ id, displayText }`; a column takes the id alone.\n\t\t\t\t\t\t\t\t\t// Reduced here so no client has to know what storage accepts, in the rows of\n\t\t\t\t\t\t\t\t\t// each declared relation too.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The whole envelope, not just `recordData` below — handlers read `ctx.args`.\n\t\t\t\t\t\t\t\t\t// Copied, not mutated: `spec.actionArgs` is the request's own value.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line oxc/no-map-spread\n\t\t\t\t\t\t\t\t\tconst argList = rawArgs.map(entry =>\n\t\t\t\t\t\t\t\t\t\tentry?.data\n\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...entry,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: unwrapInlineLinks(meta, entry.data, getMeta),\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: entry\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\t\t\t\t\t\t\t\t\tconst recordData = argList[0]?.data ?? {}\n\n\t\t\t\t\t\t\t\t\t// The database author's effect for this action, if one is registered. Keyed\n\t\t\t\t\t\t\t\t\t// by the doctype's canonical name so a slug-resolved lookup above cannot\n\t\t\t\t\t\t\t\t\t// silently miss it.\n\t\t\t\t\t\t\t\t\tconst handler = options.actionHandlers?.[meta.name]?.[String(spec.action)]\n\n\t\t\t\t\t\t\t\t\t// What a data write is allowed to set. Column identifiers come from the\n\t\t\t\t\t\t\t\t\t// doctype and never from the request — `args` is an opaque JSON scalar, so\n\t\t\t\t\t\t\t\t\t// every key in `data` is browser-supplied — which is what makes it safe to\n\t\t\t\t\t\t\t\t\t// build SQL from a patch at all.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The same derivation the read path uses, so what a record exposes is what a\n\t\t\t\t\t\t\t\t\t// record accepts. `status` is removed because state is the workflow's to\n\t\t\t\t\t\t\t\t\t// move, never the patch's. A column the database fills itself is refused in\n\t\t\t\t\t\t\t\t\t// `partitionPatch`, which asks the table only when there is a row to write:\n\t\t\t\t\t\t\t\t\t// this map is built for every action, including one on a doctype with no table.\n\t\t\t\t\t\t\t\t\tconst writable = new Map(\n\t\t\t\t\t\t\t\t\t\tcolumnBackedFields(meta.fields)\n\t\t\t\t\t\t\t\t\t\t\t.filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)\n\t\t\t\t\t\t\t\t\t\t\t.map(f => [f.fieldname, f] as const)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Whether this doctype has a workflow state to read at all. Derived from the\n\t\t\t\t\t\t\t\t\t// same declarations, so the guard cannot look for a column the doctype's own\n\t\t\t\t\t\t\t\t\t// API surface does not describe.\n\t\t\t\t\t\t\t\t\tconst declaresState = columnBackedFields(meta.fields).some(\n\t\t\t\t\t\t\t\t\t\tf => camelToSnake(f.fieldname) === STATE_COLUMN\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Reported on the result rather than logged: a dropped key is data the user\n\t\t\t\t\t\t\t\t\t// believes was saved, which is the same data-loss signal `truncatedLinks`\n\t\t\t\t\t\t\t\t\t// carries for a truncated read.\n\t\t\t\t\t\t\t\t\tconst droppedFields: string[] = []\n\t\t\t\t\t\t\t\t\t// The fields whose read value can be a linked record while the column holds\n\t\t\t\t\t\t\t\t\t// its key: one declaring a `doctype`, and one a one-side `links` entry names.\n\t\t\t\t\t\t\t\t\tconst linkFields = new Set([\n\t\t\t\t\t\t\t\t\t\t...flattenFields(meta.fields)\n\t\t\t\t\t\t\t\t\t\t\t.filter(field => field.kind === 'field' && Boolean(field.doctype))\n\t\t\t\t\t\t\t\t\t\t\t.map(field => field.fieldname),\n\t\t\t\t\t\t\t\t\t\t...Object.entries(meta.links ?? {})\n\t\t\t\t\t\t\t\t\t\t\t.filter(([, link]) => !isManySide(link))\n\t\t\t\t\t\t\t\t\t\t\t.map(([linkName, link]) => link.fieldname ?? linkName),\n\t\t\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\t\t\t// `stored` is the row as a read serves it, for an update; each field equal to\n\t\t\t\t\t\t\t\t\t// it is left out, so a save sending the whole record back writes what changed.\n\t\t\t\t\t\t\t\t\tconst partitionPatch = (patch: Record<string, unknown>, stored?: unknown) => {\n\t\t\t\t\t\t\t\t\t\tconst cols: string[] = []\n\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\t\t\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\t\t\t\t\t\t\tconst column = camelToSnake(key)\n\t\t\t\t\t\t\t\t\t\t\tif (!writable.has(key) || !columns.writable(meta.name, column)) {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\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\t\t\t\t\t\t\t\t\t\t\t// An expanding link reads back as a nested record while its column\n\t\t\t\t\t\t\t\t\t\t\t// holds a scalar foreign key, so a read-modify-write hands this loop\n\t\t\t\t\t\t\t\t\t\t\t// an object bound for a key column.\n\t\t\t\t\t\t\t\t\t\t\tif (linkFields.has(key) && value !== null && typeof value === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\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\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\tstored instanceof Object &&\n\t\t\t\t\t\t\t\t\t\t\t\tObject.hasOwn(stored, key) &&\n\t\t\t\t\t\t\t\t\t\t\t\tsameJsonValue(Reflect.get(stored, key), value)\n\t\t\t\t\t\t\t\t\t\t\t) {\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\t\t\t\t\t\t\t\t\t\t\tconst encoded = columns.encode(meta.name, column, value)\n\t\t\t\t\t\t\t\t\t\t\tif ('refused' in encoded) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`${actionDef.label ?? spec.action} failed: \"${key}\" ${encoded.refused}.`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcols.push(column)\n\t\t\t\t\t\t\t\t\t\t\tvalues.push(encoded.value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn { cols, values }\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// One transaction spans the guard read, the effect and the state write, so an\n\t\t\t\t\t\t\t\t\t// action either lands whole or not at all. `withTransaction` issues `begin` at\n\t\t\t\t\t\t\t\t\t// the top level and a `savepoint` if something upstream already opened one, so\n\t\t\t\t\t\t\t\t\t// nesting is safe rather than something callers must avoid.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// Every statement below runs on `tx`, not on the outer client. Work sent to the\n\t\t\t\t\t\t\t\t\t// outer client — or to a connection a handler opens itself — is outside this\n\t\t\t\t\t\t\t\t\t// transaction and would survive a rollback.\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await pgClient.withTransaction(async (tx: PgClient) => {\n\t\t\t\t\t\t\t\t\t\t\tconst outcome = await applyGuardedTransition(\n\t\t\t\t\t\t\t\t\t\t\t\tactionDef,\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\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// A save is filed under the record's key, so a doctype without one\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// cannot save, even a record not created yet.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true) pkColumn()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No id in the envelope means no record was targeted at all, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the same answer as a lookup that misses: `null`, not `undefined`.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Selecting `status` unconditionally made this read fail outright on\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// any table without that column — and a self-transition reaches here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// not to read a state but to learn whether the row exists, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// what decides create vs. update. So the projection follows the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// doctype: a doctype that declares no state field has none to read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and the honest answer for a row it finds is \"exists, no state\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (Measured: 24 of FAB's 35 guarded tables have no `status` column.)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst projection = declaresState ? `\"${STATE_COLUMN}\"` : `\"${pkColumn()}\"`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FOR UPDATE holds the row until this transaction ends, so a second\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// action on the same record waits rather than reading the same state\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and acting on it too. Without it the guard is a check-then-act\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// race: two concurrent approvals both read PENDING and both proceed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, string | null>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${projection} FROM ${table} WHERE \"${pkColumn()}\"::text = $1 FOR UPDATE`,\n\t\t\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\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (rows.length === 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// An id that was dispatched and matched nothing is a record that has\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// gone away since the client read it, and saving it as a create mints\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// a second row under a new identity while the client believes it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// updated the first: a lost update that reports success. Refused here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// before the adapter's write or a registered handler can run.\n\t\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\t// The dispatcher cannot make this call: it never receives the id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// deliberately, since identity is the backend's business. So the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// distinction its `readState` contract collapses is restored here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// where the id is in scope.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`${actionDef.label ?? spec.action} failed: record ${String(recordId)} no longer exists.`\n\t\t\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\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn null\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\tif (!declaresState) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0][STATE_COLUMN] ?? undefined\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\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"${STATE_COLUMN}\" = $1 WHERE \"${pkColumn()}\"::text = $2`,\n\t\t\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\t\t})\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\t// The upsert, and the write path for record data unless a handler is\n\t\t\t\t\t\t\t\t\t\t\t\t\t// registered for the Save. `exists` comes from the guard's own read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t// so no second lookup decides it.\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\t// Returns the same projection the read path selects, never\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `RETURNING *`: raw columns come back snake_case, and the client\n\t\t\t\t\t\t\t\t\t\t\t\t\t// resolves identity by the *declared fieldname*. A doctype keyed\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `itemId` would receive `item_id`, find no identity, and file a\n\t\t\t\t\t\t\t\t\t\t\t\t\t// created record nowhere — which is that exact bug, already once\n\t\t\t\t\t\t\t\t\t\t\t\t\t// shipped and patched downstream.\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteData: async (patch: Record<string, unknown>, exists: boolean) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst returning = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { cols, values } = partitionPatch(patch)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Creating is what the *absence* of an id means; `readState` has\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// already refused an id that matched no row.\n\t\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\t// No identity is minted here. A declared key present in the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// patch is a natural key the user filled in and passes\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// through the whitelist like any other column; absent, the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// column default supplies it. Either way the row states its\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// own identity back.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst text = cols.length\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? `INSERT INTO ${table} (${cols.map(c => `\"${c}\"`).join(', ')}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(', ')}) RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, { text, values })\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\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\t\t// The row as a read serves it, locked by the guard's read, to tell what\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the patch changes. An expanding link's field is compared with its key,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// since the read serves it as the linked record, so an empty link is null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// on both sides. Put through JSON as the client's copy was, so a value\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// JSON cannot hold (a Buffer, NaN) compares as it arrives.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst linkKeys = linkKeySelections(meta)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst storedSelect = columns.select(meta.name, [...getColumnSelections(meta), ...linkKeys])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: storedRows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${storedSelect.list} FROM ${table} WHERE \"${pkColumn()}\"::text = $1`,\n\t\t\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\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstoredSelect.decodeRows(storedRows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst stored = storedRows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst compared: Record<string, unknown> = { ...stored }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor (const { fieldname, alias } of linkKeys) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcompared[fieldname] = stored[alias]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdelete compared[alias]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdelete stored[alias]\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 { cols, values } = partitionPatch(patch, JSON.parse(JSON.stringify(compared)))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Nothing changed, or nothing writable survived the patch. `SET` with\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// no assignments is a syntax error, and reporting failure would be\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// wrong: the record is fine and unchanged, so it is what the reply\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// carries, with `droppedFields` saying what was left out.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (cols.length === 0) return stored\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst assignments = cols\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.map((c, i) => `\"${c}\" = ${columns.bind(meta.name, c, `$${i + 1}`)}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET ${assignments} WHERE \"${pkColumn()}\"::text = $${cols.length + 1} RETURNING ${returning.list}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [...values, String(recordId)],\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\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\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\trunEffect: handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (currentState: string | undefined) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thandler({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpgClient: tx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoctype: String(spec.doctype),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taction: String(spec.action),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trecordId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata: recordData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\targs: argList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentState,\n\t\t\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: undefined,\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\t// The patch a self-transition persists. This adapter never passed it, which\n\t\t\t\t\t\t\t\t\t\t\t\t// was moot while it had no `writeData` — nothing consumed it. Wiring the write\n\t\t\t\t\t\t\t\t\t\t\t\t// without this argument saves an empty record and reports success.\n\t\t\t\t\t\t\t\t\t\t\t\trecordData\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// `applyGuardedTransition` REPORTS failure, it does not throw — a refused\n\t\t\t\t\t\t\t\t\t\t\t// guard and a handler that blew up both come back as `{ success: false }`.\n\t\t\t\t\t\t\t\t\t\t\t// Returning that normally would commit the transaction, so a handler that\n\t\t\t\t\t\t\t\t\t\t\t// wrote three rows and then threw would keep all three. Throwing here is\n\t\t\t\t\t\t\t\t\t\t\t// what makes the rollback happen; the envelope is carried across so the\n\t\t\t\t\t\t\t\t\t\t\t// caller still gets `success: false` rather than a GraphQL error.\n\t\t\t\t\t\t\t\t\t\t\tif (!outcome.success) throw new ActionRolledBack(outcome)\n\n\t\t\t\t\t\t\t\t\t\t\t// The identity the reply states, read before enrichment below turns a key\n\t\t\t\t\t\t\t\t\t\t\t// that is also a link into `{ id, displayText }`, which no read can look up.\n\t\t\t\t\t\t\t\t\t\t\tconst pkField = getPkMeta(meta)?.fieldname\n\t\t\t\t\t\t\t\t\t\t\tconst repliedId: unknown =\n\t\t\t\t\t\t\t\t\t\t\t\tpkField !== undefined && outcome.data !== null && typeof outcome.data === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Reflect.get(outcome.data, pkField)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined\n\n\t\t\t\t\t\t\t\t\t\t\t// A record a write returns is a record, so it carries the links a read\n\t\t\t\t\t\t\t\t\t\t\t// resolves. Enriching one path and not the other changes a record's\n\t\t\t\t\t\t\t\t\t\t\t// shape depending on how the client came by it: a link rendered its\n\t\t\t\t\t\t\t\t\t\t\t// display text until the record was saved, and its raw id from then\n\t\t\t\t\t\t\t\t\t\t\t// until the next full fetch. Nothing fails — the field just goes wrong.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Runs inside the transaction so the lookup sees the row just written,\n\t\t\t\t\t\t\t\t\t\t\t// and only on success, since a rolled-back action returns no record.\n\t\t\t\t\t\t\t\t\t\t\t// A result that is not a record at all — an effect's `{ state }` — has\n\t\t\t\t\t\t\t\t\t\t\t// no field the doctype declares as an inline link, so it is untouched.\n\t\t\t\t\t\t\t\t\t\t\tif (outcome.success && outcome.data !== null && typeof outcome.data === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\t// A predicate rather than an assertion: an element that is not an object has\n\t\t\t\t\t\t\t\t\t\t\t\t// no field to enrich, so dropping it is the honest answer.\n\t\t\t\t\t\t\t\t\t\t\t\tconst written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t(row: unknown): row is Record<string, unknown> => row !== null && typeof row === 'object'\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\tawait enrichLinkDisplayFields(tx, meta, written, columns, debugSql)\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// The record as a read returns it, whoever wrote it: the client files this,\n\t\t\t\t\t\t\t\t\t\t\t// never `data`, which stays the handler's own. Keyed by the declared identity\n\t\t\t\t\t\t\t\t\t\t\t// the reply states when it states one, since an action may create or re-key\n\t\t\t\t\t\t\t\t\t\t\t// the record, and by the dispatched id otherwise.\n\t\t\t\t\t\t\t\t\t\t\tconst readId = repliedId ?? recordId\n\t\t\t\t\t\t\t\t\t\t\tconst record =\n\t\t\t\t\t\t\t\t\t\t\t\treadId == null\n\t\t\t\t\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t: ((await readRecords(tx, [{ doctype: meta.name, id: readId }]))[0]?.data ?? null)\n\n\t\t\t\t\t\t\t\t\t\t\t// A save with no record to file leaves the page on its draft, whose next save\n\t\t\t\t\t\t\t\t\t\t\t// creates a second record.\n\t\t\t\t\t\t\t\t\t\t\tif (actionDef.selfTransition === true && record === null) {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new ActionRolledBack({\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\t\t\terror: `${actionDef.label ?? spec.action} failed: the server did not say which record it saved.`,\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// Attached here rather than carried through `applyGuardedTransition`:\n\t\t\t\t\t\t\t\t\t\t\t// which keys a backend can store is a storage question, and the\n\t\t\t\t\t\t\t\t\t\t\t// dispatcher is deliberately storage-agnostic. A failed action wrote\n\t\t\t\t\t\t\t\t\t\t\t// nothing, so the list is only meaningful on success.\n\t\t\t\t\t\t\t\t\t\t\tconst reply = { ...outcome, record }\n\t\t\t\t\t\t\t\t\t\t\treturn droppedFields.length ? { ...reply, droppedFields } : reply\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\tif (err instanceof ActionRolledBack) return err.outcome\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\treturn {\n\t\t...schemaPlugin,\n\t\tgather: {\n\t\t\thooks: {\n\t\t\t\t// Marks a column Postgres generates as neither insertable nor updatable, as PostGraphile\n\t\t\t\t// itself marks an identity generated always. PostGraphile reads `attgenerated` only into\n\t\t\t\t// `hasDefault`, which a plain default shares, so without this the data write cannot tell\n\t\t\t\t// the two apart. On the adapter's plugin rather than the preset, so it holds wherever the\n\t\t\t\t// write runs.\n\t\t\t\tpgCodecs_attribute(_info, event) {\n\t\t\t\t\tconst { attgenerated } = event.pgAttribute\n\t\t\t\t\tif (attgenerated == null || attgenerated === '') return\n\t\t\t\t\tevent.attribute.extensions ??= {}\n\t\t\t\t\tevent.attribute.extensions.isInsertable = false\n\t\t\t\t\tevent.attribute.extensions.isUpdatable = false\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 * Derive column selections 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>): ColumnSelection[] {\n\tconst columns: ColumnSelection[] = []\n\tfor (const f of columnBackedFields(fields)) {\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// rule both sides of the wire share; 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\tcolumns.push({ column: camelToSnake(f.fieldname), alias: f.fieldname })\n\t}\n\treturn columns\n}\n\n/**\n * Derive the columns a record payload selects from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, and keeps\n * the fieldname as its alias 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 getColumnSelections(meta: DoctypeMeta): ColumnSelection[] {\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)\n}\n\n/**\n * Resolve the declared field this doctype's records are looked up by.\n *\n * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the\n * client's record keying name the same field — including the `id` fallback, whose absence here\n * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the\n * client and refused outright by this adapter, so every fetch answered `null` and looked exactly\n * like a record that does not exist.\n *\n * Returns `undefined` only when the resolved name is not a declared field — a doctype with no\n * `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields\n * only, so the row map would key on a column the SELECT never returned and every lookup would miss\n * silently. Callers must say so rather than answer `null`.\n *\n * Descends into fieldsets, because both halves of the question already do — `getColumnSelections` selects\n * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this\n * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose\n * SELECT carried its own key column had no identity to look that column up by.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\tconst fieldname = getRecordIdField(meta.fields)\n\treturn flattenFields(meta.fields).find((f): f is ValueField => f.kind === 'field' && f.fieldname === fieldname)\n}\n\n/**\n * The ORDER BY clause for reading a doctype's rows: the field `order` names, then the declared identity\n * to break ties, or the identity alone when nothing is named. Empty when the doctype declares no identity\n * and nothing is named.\n *\n * One definition for the list query and for a many-side link, which both cap what they read. A capped read\n * without a total order keeps an arbitrary set of rows, a different one whenever a row is updated and moves\n * in the heap, and only the identity is unique. Without an identity there is no stable key, and inventing\n * one would be a guess.\n *\n * Each term names its column through `table`, the statement's FROM. The select returns every column as text\n * under its fieldname, and a field named as its column (`position`, `id`, `created_at`) shares that name;\n * ORDER BY reads a bare name as the output column first, so it sorted that text and 10 came before 9.\n * Qualified, the name can only mean the column, compared as its own type.\n *\n * The named field must have a column (`columnBackedFields`): a computed field has none, and naming one would\n * reach Postgres as a missing column instead of being refused by name.\n */\nfunction orderClause(meta: DoctypeMeta, order: LinkDeclaration['orderBy'], table: string): string {\n\tconst terms: string[] = []\n\tif (order !== undefined) {\n\t\tif (!columnBackedFields(meta.fields).some(field => field.fieldname === order.fieldname)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown orderBy field: \"${order.fieldname}\" for doctype ${meta.name}; an order names a field with a database column`\n\t\t\t)\n\t\t}\n\t\tterms.push(`${table}.\"${camelToSnake(order.fieldname)}\" ${order.direction === 'desc' ? 'DESC' : 'ASC'}`)\n\t}\n\tconst pkMeta = getPkMeta(meta)\n\tif (pkMeta && pkMeta.fieldname !== order?.fieldname) {\n\t\tterms.push(`${table}.\"${camelToSnake(pkMeta.fieldname)}\" ASC`)\n\t}\n\treturn terms.length > 0 ? ` ORDER BY ${terms.join(', ')}` : ''\n}\n\n/**\n * The list query's `orderBy` argument, `FIELD_ASC` or `FIELD_DESC` with the direction in either case, read\n * as the order a link declares. The field is everything before the last underscore, so it may hold\n * underscores of its own.\n */\nfunction readListOrderBy(orderBy: string): NonNullable<LinkDeclaration['orderBy']> {\n\tconst lastUnder = orderBy.lastIndexOf('_')\n\tif (lastUnder <= 0) {\n\t\tthrow new Error(`Invalid orderBy format: \"${orderBy}\". Expected FIELD_ASC or FIELD_DESC`)\n\t}\n\tconst direction = orderBy.slice(lastUnder + 1).toLowerCase()\n\tif (direction !== 'asc' && direction !== 'desc') {\n\t\tthrow new Error(`Invalid orderBy direction: \"${direction.toUpperCase()}\". Must be ASC or DESC`)\n\t}\n\treturn { fieldname: orderBy.slice(0, lastUnder), direction }\n}\n\n/**\n * Assert that every registered action handler names a doctype and an action that exist.\n *\n * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler\n * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.\n * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it\n * has one, the missing effect is skipped and the state write still reports success. So renaming a\n * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.\n *\n * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a\n * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a\n * real doctype here and still never fires. It is reported as its own case rather than as \"unknown\n * doctype\", because the repair is different.\n *\n * Throws rather than warns: there is no legitimate reason to register a handler for an action that\n * does not exist, and the alternative is a silent half-executed workflow. Every offender is\n * collected so a consumer with several fixes them in one pass.\n */\nfunction assertActionHandlersResolve(actionHandlers: Record<string, Record<string, ActionHandler>>): void {\n\t// Nothing registered, nothing to check.\n\tconst registered = Object.entries(actionHandlers)\n\tif (registered.length === 0) return\n\n\t// An empty registry cannot tell \"this key is stale\" from \"doctypes have not loaded yet\" — a\n\t// host is free to build the schema before its loader runs. Warn on that ambiguity rather than\n\t// failing a boot that is merely early.\n\tif (getAllMeta().length === 0) {\n\t\t// oxlint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +\n\t\t\t\t'`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +\n\t\t\t\t'have stale handler keys reported.'\n\t\t)\n\t\treturn\n\t}\n\n\tconst orphans: string[] = []\n\tfor (const [doctypeKey, handlers] of registered) {\n\t\tconst meta = getMeta(doctypeKey)\n\t\tif (!meta) {\n\t\t\torphans.push(`\"${doctypeKey}\": no doctype by that name is registered`)\n\t\t\tcontinue\n\t\t}\n\t\tif (meta.name !== doctypeKey) {\n\t\t\torphans.push(\n\t\t\t\t`\"${doctypeKey}\": matches the doctype named \"${meta.name}\" by slug, but handlers are looked up by name — key it \"${meta.name}\"`\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst actions = meta.workflow?.actions ?? {}\n\t\tfor (const actionKey of Object.keys(handlers)) {\n\t\t\tif (!(actionKey in actions)) {\n\t\t\t\torphans.push(`\"${doctypeKey}.${actionKey}\": the doctype declares no action by that key`)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (orphans.length > 0) {\n\t\tthrow new Error(\n\t\t\t`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +\n\t\t\t\t`cannot be reached and would never run:\\n ${orphans.join('\\n ')}`\n\t\t)\n\t}\n}\n\n/**\n * Refuse a doctype set whose links or `inherits` name a doctype nobody registered, or whose links\n * bind or order by a field that cannot serve (see `validateReferences`).\n *\n * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed\n * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response\n * with no error. On the wire that is indistinguishable from \"this record has no such relation\", and\n * a typo in a target reads as a legitimately empty link forever.\n *\n * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not\n * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.\n *\n * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns\n * because a registered handler map is evidence the host meant to be checked; here there is no such\n * evidence, so warning would fire on every host that loads doctypes after building its schema —\n * and an advisory that fires on a correct setup is worse than none. An empty registry simply\n * reports nothing, because the loop has nothing to walk.\n */\nfunction assertReferencesResolve(): void {\n\tconst broken = validateReferences()\n\tif (broken.length === 0) return\n\n\tthrow new Error(\n\t\t`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +\n\t\t\t`cannot be resolved; each says what it breaks:\\n ` +\n\t\t\tbroken.map(e => `${e.path.join('.')}: ${e.message}`).join('\\n ')\n\t)\n}\n\n/**\n * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype\n * and both repairs. Shared so the three lookup sites report one diagnosis.\n */\nfunction unresolvableIdentityError(doctype: string): Error {\n\treturn new Error(\n\t\t`Doctype \"${doctype}\" has no identity field: it declares no field with \\`primaryKey: true\\` ` +\n\t\t\t`and no field named \\`id\\`. Declare one of the two — records cannot be fetched or acted on until then.`\n\t)\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 */\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 *\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\n/**\n * Stops Amber taking `id` for Relay's global object identifier.\n *\n * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called\n * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware\n * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`\n * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not\n * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that\n * node id and every read of it then fails on a missing column.\n *\n * Both inflectors must move together. Undoing the rename alone collides with the Relay field still\n * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called\n * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier\n * to `nodeId` keeps Relay working and is the name the schema converter already skips.\n *\n * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.\n */\nconst StonecropNaturalIdPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNaturalIdPlugin',\n\tversion: '0.0.0',\n\tafter: ['PgAttributesPlugin'],\n\tinflection: {\n\t\treplace: {\n\t\t\t// Move Relay's global identifier off `id`...\n\t\t\tnodeIdFieldName() {\n\t\t\t\treturn 'nodeId'\n\t\t\t},\n\n\t\t\t// ...so the real column can keep its own name.\n\t\t\t_attributeName(previous, options, details) {\n\t\t\t\t// `previous` is optional in the inflector signature because a replacement may be the first\n\t\t\t\t// implementation. It never is here — `after: ['PgAttributesPlugin']` guarantees Amber's runs\n\t\t\t\t// first — but the raw attribute name is the correct identity fallback.\n\t\t\t\tconst name = previous?.(details) ?? details.attributeName\n\t\t\t\tif (!details.skipRowId && name === 'row_id') {\n\t\t\t\t\tconst { codec, attributeName } = details\n\t\t\t\t\tconst baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName\n\t\t\t\t\tif (typeof baseName === 'string' && baseName.toLowerCase() === 'id' && !codec.isAnonymous) {\n\t\t\t\t\t\treturn 'id'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn name\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Exposes the many side of a foreign key the database declares as owning.\n *\n * PostGraphile registers both directions of every foreign key, but Amber gives the many side no\n * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s\n * inferred behavior is `[\"resource:select\", behavior]` and nothing more. So a parent type carries\n * no field for its children, and a doctype generated from that schema can never contain a child\n * table. Every one a consumer has is hand-authored.\n *\n * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.\n * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`\n * does not: an order references a party that outlives it. The two are otherwise the same shape, so\n * no amount of reading the relation itself can separate them — and turning the many side on for\n * *every* foreign key would make each referenced table look like somebody's child.\n *\n * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw\n * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.\n *\n * Connection only, deliberately. The converter recognises a Connection type through\n * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`\n * would add a second field per relation that generation then drops on the floor.\n *\n * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the\n * global default and take precedence, so `+manyRelation:resource:connection` there is overridden\n * for every relation — verified, it changes nothing, while `-connection +list` through the same\n * option visibly rewrites the Query fields.\n */\nconst StonecropOwnedRelationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropOwnedRelationsPlugin',\n\tversion: '0.0.0',\n\tgather: {\n\t\thooks: {\n\t\t\tpgRelations_relation(_info, event) {\n\t\t\t\tconst { relation, pgConstraint } = event\n\t\t\t\t// The hook fires once per direction of each constraint; only the backwards one has a\n\t\t\t\t// many side to expose. `confdeltype` is Postgres' own code: 'c' is CASCADE.\n\t\t\t\tif (!relation.isReferencee) return\n\t\t\t\tif (pgConstraint.confdeltype !== 'c') return\n\n\t\t\t\trelation.extensions ??= {}\n\t\t\t\trelation.extensions.tags ??= {}\n\t\t\t\trelation.extensions.tags.behavior = '+manyRelation:resource:connection'\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Offers no database function as a mutation.\n *\n * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard\n * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds\n * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.\n */\nconst StonecropNoFunctionMutationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNoFunctionMutationsPlugin',\n\tversion: '0.0.0',\n\tschema: {\n\t\tentityBehavior: {\n\t\t\tpgResource: {\n\t\t\t\toverride: {\n\t\t\t\t\t// After the hook that applies smart tags, so an app's `@behavior +mutationField` cannot undo it.\n\t\t\t\t\tafter: ['PgBasicsPlugin'],\n\t\t\t\t\tcallback(behavior) {\n\t\t\t\t\t\treturn [behavior, '-mutationField']\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n}\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. It turns off the mutations Amber generates, a create, update and delete for\n * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write\n * the API offers. 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: [\n\t\tStonecropNaturalIdPlugin,\n\t\tStonecropOwnedRelationsPlugin,\n\t\tStonecropNoFunctionMutationsPlugin,\n\t\t...(options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : []),\n\t],\n\t// Every write is an action, through `stonecropAction`, and Amber's create, update and delete for\n\t// each table would write past the doctype's guard. Disabled rather than set in\n\t// `schema.defaultBehavior`, which an app's own `defaultBehavior` replaces whole; `disablePlugins`\n\t// lists merge.\n\tdisablePlugins: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin'],\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,mBAAmB,QAA+C;CACjF,OAAOA,gBAAc,MAAM,CAAC,CAAC,QAAQ,MAAuB,EAAE,SAAS,WAAW,CAAC,EAAE,QAAQ;AAC9F;;ACtBA,IAAM,kCAA4C,IAAI,IAAI;;;;;AAM1D,IAAa,yBAAb,cAA4C,MAAM;CAGhC;CAEA;CAJjB,YAEC,MAEA,QACC;EACD,MAAM,gBAAgB,OAAO,KAAI,MAAK,KAAK,EAAE,KAAK,KAAK,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,KAAK,IAAI;EACtF,MAAM,iCAAiC,KAAK,KAAK,eAAe;EALhD,KAAA,OAAA;EAEA,KAAA,SAAA;EAIhB,KAAK,OAAO;CACb;AACD;;;;;;;AAmBA,SAAgB,aAAa,KAAa,UAA+B,CAAC,GAAS;CAClF,MAAM,UAAU,YAAY,GAAG;CAE/B,KAAK,MAAM,SAAS,SAAS;EAC5B,MAAM,WAAW,KAAK,KAAK,KAAK;EAGhC,IAFa,SAAS,QAElB,CAAA,CAAK,YAAY,GACpB,aAAa,UAAU,OAAO;OACxB,IAAI,MAAM,SAAS,OAAO,GAChC,gBAAgB,UAAU,OAAO;CAEnC;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UAAU,iBAAiB;EAGnC,IAAI,CAAC,SAAS,cAAc;EAC5B,IAAI,aAAa,gBAAgB,KAAK;EAEtC,SAAS,eAAe,CAAC;EACzB,SAAS,WAAW,SAAS,CAAC;EAC9B,SAAS,WAAW,KAAK,WAAW;CACrC,EACD,EACD;AACD;;;;;;;;AASA,IAAM,qCAA4D;CACjE,MAAM;CACN,SAAS;CACT,QAAQ,EACP,gBAAgB,EACf,YAAY,EACX,UAAU;EAET,OAAO,CAAC,gBAAgB;EACxB,SAAS,UAAU;GAClB,OAAO,CAAC,UAAU,gBAAgB;EACnC;CACD,EACD,EACD,EACD;AACD;AAEA,IAAM,6BAAoD;CACzD,MAAM;CACN,SAAS;CACT,YAAY,EACX,SAAS,EACR,UAAU,UAAU,SAAS,SAAS;EACrC,OAAO,KAAK,eAAe,KAAK,eAAe,OAAO,CAAC;CACxD,EACD,EACD;AACD;;;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAa,yBAAyB,aAAoE;CACzG,SAAS,CAAC,uBAAuB;CACjC,SAAS;EACR;EACA;EACA;EACA,GAAI,SAAS,gBAAgB,WAAW,CAAC,0BAA0B,IAAI,CAAC;CACzE;CAKA,gBAAgB,CAAC,0BAA0B,8BAA8B;AAC1E;;;;;;;;;;;;;;;;;;AAmBA,IAAa,kBAAyC,sBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stonecrop/graphql-middleware",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.60.0",
|
|
4
4
|
"description": "GraphQL middleware for PostGraphile and Stonecrop schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"graphql",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"graphql": "^16.14.0",
|
|
42
42
|
"postgraphile": "^5.0.3",
|
|
43
43
|
"temporal-polyfill": "^1.0.5",
|
|
44
|
-
"@stonecrop/schema": "0.
|
|
44
|
+
"@stonecrop/schema": "0.60.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@electric-sql/pglite": "^0.5.8",
|