@stonecrop/graphql-middleware 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/index.js +1188 -720
  2. package/dist/index.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -14
  5. package/dist/graphql_client.tsbuildinfo +0 -1
  6. package/dist/src/debug.d.ts +0 -31
  7. package/dist/src/debug.d.ts.map +0 -1
  8. package/dist/src/debug.js +0 -49
  9. package/dist/src/dispatch/transition.d.ts +0 -107
  10. package/dist/src/dispatch/transition.d.ts.map +0 -1
  11. package/dist/src/dispatch/transition.js +0 -152
  12. package/dist/src/fields.d.ts +0 -23
  13. package/dist/src/fields.d.ts.map +0 -1
  14. package/dist/src/fields.js +0 -28
  15. package/dist/src/index.d.ts +0 -16
  16. package/dist/src/index.d.ts.map +0 -1
  17. package/dist/src/index.js +0 -14
  18. package/dist/src/link-display.d.ts +0 -19
  19. package/dist/src/link-display.d.ts.map +0 -1
  20. package/dist/src/link-display.js +0 -93
  21. package/dist/src/plugin/postgraphile.d.ts +0 -174
  22. package/dist/src/plugin/postgraphile.d.ts.map +0 -1
  23. package/dist/src/plugin/postgraphile.js +0 -882
  24. package/dist/src/preset.d.ts +0 -53
  25. package/dist/src/preset.d.ts.map +0 -1
  26. package/dist/src/preset.js +0 -148
  27. package/dist/src/registry/doctypes.d.ts +0 -95
  28. package/dist/src/registry/doctypes.d.ts.map +0 -1
  29. package/dist/src/registry/doctypes.js +0 -251
  30. package/dist/src/registry/fetchHandlers.d.ts +0 -31
  31. package/dist/src/registry/fetchHandlers.d.ts.map +0 -1
  32. package/dist/src/registry/fetchHandlers.js +0 -24
  33. package/dist/src/tables.d.ts +0 -14
  34. package/dist/src/tables.d.ts.map +0 -1
  35. package/dist/src/tables.js +0 -21
  36. package/dist/src/typeDefs.d.ts +0 -7
  37. package/dist/src/typeDefs.d.ts.map +0 -1
  38. package/dist/src/typeDefs.js +0 -118
@@ -1,882 +0,0 @@
1
- import { camelToSnake, getRecordIdField, resolveLinkRenderMode, unwrapInlineLinks } from '@stonecrop/schema';
2
- import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
3
- import { constant, lambda, object } from 'postgraphile/grafast';
4
- import { extendSchema } from 'postgraphile/utils';
5
- import { columnBackedFields, flattenFields } from '../fields';
6
- import { enrichLinkDisplayFields } from '../link-display';
7
- import { resolveTableName } from '../tables';
8
- import { getFetchHandler } from '../registry/fetchHandlers';
9
- import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
10
- import { applyGuardedTransition } from '../dispatch/transition';
11
- import { typeDefs } from '../typeDefs';
12
- /**
13
- * Carries a reported failure out through a `throw`, purely so the transaction rolls back.
14
- *
15
- * `applyGuardedTransition` reports every failure as a return value, and a value returned from
16
- * inside `withTransaction` commits. This is the adapter between "the action failed" and "undo it"
17
- * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and
18
- * answers with the original envelope.
19
- */
20
- class ActionRolledBack extends Error {
21
- outcome;
22
- constructor(outcome) {
23
- super(outcome.error ?? 'Action failed');
24
- this.outcome = outcome;
25
- this.name = 'ActionRolledBack';
26
- }
27
- }
28
- /**
29
- * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
30
- * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getSqlColumns`
31
- * omits its FK column by design — but the expansion needs the value to find the target. Aliasing
32
- * keeps that need from changing the payload: every alias is stripped before the record is returned.
33
- */
34
- const LINK_FK_ALIAS = '__stonecropLinkFk_';
35
- /**
36
- * The column this adapter keeps a record's workflow state in.
37
- *
38
- * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,
39
- * the transition's write, and the data write that must refuse to touch it. A patch that could set
40
- * this column would let any client walk past `allowedStates` by writing the very value the guard
41
- * reads.
42
- */
43
- const STATE_COLUMN = 'status';
44
- /**
45
- * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
46
- *
47
- * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
48
- * during schema construction — it does not need to be supplied by the caller.
49
- *
50
- * @param options - Optional plugin configuration
51
- * @returns A PostGraphile plugin
52
- * @public
53
- */
54
- export const createStonecropPlugin = (options = {}) => {
55
- /**
56
- * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging
57
- * for queries that run inside custom loadOneWithPgClient callbacks, which
58
- * bypass the executor's native instrumentation.
59
- */
60
- const debugSql = options.debug
61
- ? (pgClient, query) => {
62
- // oxlint-disable-next-line no-console
63
- console.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? []);
64
- return pgClient.query(query);
65
- }
66
- : (pgClient, query) => pgClient.query(query);
67
- // Resolved once, for both read paths. `undefined` means "not configured" and `null` means
68
- // "configured off", which is a distinction `??` cannot make — and the two paths disagreeing
69
- // about it is exactly how a link came to be capped by a different number than a list.
70
- const defaultRowLimit = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit;
71
- return extendSchema(build => {
72
- // Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
73
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type
74
- const pgExecutors = build.input?.pgRegistry?.pgExecutors;
75
- const executor = pgExecutors ? Object.values(pgExecutors)[0] : undefined;
76
- if (!executor) {
77
- throw new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured');
78
- }
79
- // Schema build is the one point where both the registry and the plugin's options are in
80
- // hand, so it is where a stale registration can be caught before it silently no-ops.
81
- if (options.actionHandlers)
82
- assertActionHandlersResolve(options.actionHandlers);
83
- assertReferencesResolve();
84
- return {
85
- typeDefs,
86
- objects: {
87
- Query: {
88
- plans: {
89
- stonecropMeta(_, { $doctype }) {
90
- return lambda($doctype, (doctype) => {
91
- const meta = getMeta(String(doctype));
92
- return meta ?? null;
93
- });
94
- },
95
- stonecropAllMeta() {
96
- return constant(getAllMeta());
97
- },
98
- stonecropRecord(_, { $doctype, $id, $options }) {
99
- return loadOneWithPgClient(executor, object({ doctype: $doctype, id: $id, options: $options }), async (pgClient, specs) => {
100
- // Group specs by doctype to batch the main SELECT per table
101
- const byDoctype = new Map();
102
- for (let i = 0; i < specs.length; i++) {
103
- const d = String(specs[i].doctype);
104
- if (!byDoctype.has(d))
105
- byDoctype.set(d, []);
106
- byDoctype.get(d).push(i);
107
- }
108
- const results = Array.from({ length: specs.length });
109
- for (const [doctype, indices] of byDoctype) {
110
- const meta = getMeta(doctype);
111
- if (!meta) {
112
- for (const i of indices)
113
- results[i] = { data: null, doctype };
114
- continue;
115
- }
116
- // Not `data: null` — that is the answer for a record that does not exist, and a
117
- // doctype nobody can look up is a misconfiguration, not an empty result.
118
- const pkMeta = getPkMeta(meta);
119
- if (!pkMeta)
120
- throw unresolvableIdentityError(doctype);
121
- const pkColumn = camelToSnake(pkMeta.fieldname);
122
- const columns = getSqlColumns(meta);
123
- const ids = indices.map(i => String(specs[i].id));
124
- // Resolved once per doctype: how each link renders, and which foreign keys the
125
- // SELECT must carry for the expansion below to work at all.
126
- //
127
- // `resolveLinkRenderMode` needs the linked field's own component, so the fields
128
- // are indexed by name — flattened, because a link's field may sit inside a
129
- // fieldset and `getSqlColumns` already descends to select it.
130
- const fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]));
131
- const linkFkAliases = [];
132
- for (const [linkName, link] of Object.entries(meta.links ?? {})) {
133
- // Many-side links find their rows by a column on the *target*; only a one-side
134
- // link reads a foreign key off this row.
135
- if (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne')
136
- continue;
137
- const fieldname = link.fieldname ?? linkName;
138
- // An inline link keeps its FK as a scalar, so `getSqlColumns` already selected
139
- // it under its own name and no alias is needed.
140
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
141
- continue;
142
- linkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` });
143
- }
144
- const selectList = [
145
- columns,
146
- ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`),
147
- ]
148
- .filter(Boolean)
149
- .join(', ');
150
- // TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;
151
- // requires refactoring the grouped-by-doctype loop to collect promises before resolving results
152
- // oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above
153
- const { rows } = await debugSql(pgClient, {
154
- text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
155
- values: [ids],
156
- });
157
- // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
158
- const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
159
- // A declared key the database does not actually enforce as unique collapses several
160
- // rows into that Map, and it keeps whichever came last — one arbitrary record,
161
- // returned as though it were *the* record, with nothing to say so. Refuse instead.
162
- //
163
- // This is exact rather than a proxy for the problem: `ANY` matches each requested id
164
- // once, so a shortfall here means two distinct rows genuinely share a key value. A
165
- // `pg_index` check would instead ask whether a unique constraint exists, which is the
166
- // cause rather than the harm — and would flag a column that is unique in practice but
167
- // unconstrained, which is a real and common shape.
168
- if (rows.length !== rowByPk.size) {
169
- throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column ` +
170
- `is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +
171
- `matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +
172
- `Declare a field that uniquely identifies a record, or add a unique constraint.`);
173
- }
174
- // Collected across the batch so the display lookup runs once for all of them.
175
- // Called per row inside this loop it issued one query per record per link field,
176
- // which is the N+1 this batched loader exists to avoid — and silently, since the
177
- // enriched rows come out identical either way.
178
- const enrichedRows = [];
179
- for (const i of indices) {
180
- const specId = String(specs[i].id);
181
- const row = rowByPk.get(specId);
182
- if (!row) {
183
- results[i] = { data: null, doctype };
184
- continue;
185
- }
186
- const rowData = { ...row };
187
- enrichedRows.push(rowData);
188
- // Per record, not per doctype: two records of one doctype can differ in whether
189
- // a relation overflowed, and a shared list would report the wrong one truncated.
190
- const truncatedLinks = [];
191
- const recordOptions = (specs[i].options ?? {});
192
- const includeAll = recordOptions.includeNested === true;
193
- const includeSet = Array.isArray(recordOptions.includeNested)
194
- ? new Set(recordOptions.includeNested)
195
- : null;
196
- // FetchStrategy dispatch over link declarations
197
- if (meta.links) {
198
- for (const [linkName, link] of Object.entries(meta.links)) {
199
- // The payload key is the *resolved* fieldname, not the map key: the client
200
- // binds a link to the field named `link.fieldname ?? key` and reads the
201
- // nested data off that field, so writing under the bare key put the result
202
- // somewhere nothing looks whenever a declaration named its own `fieldname`.
203
- // Identical for every declaration that omits `fieldname`, which is all of them
204
- // in this repo — hence latent until now.
205
- const fieldname = link.fieldname ?? linkName;
206
- const fetch = link.fetch;
207
- const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
208
- const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
209
- // Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only
210
- // `SyncFetch` carries a `limit` — and the server default used to hang off its
211
- // `else`, so declaring the method a many-side link already defaults to removed
212
- // the cap entirely. "Did the author write a limit?" and "did the author write
213
- // the word sync?" are now asked separately.
214
- const declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined;
215
- const effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined;
216
- // The one gate. It used to be followed by a second test that re-asked the
217
- // same question using only `includeSet` — `null` for the boolean form — so
218
- // `includeNested: true` admitted every link here and then silently dropped
219
- // each non-`sync` one, handing back a partial record with no way to tell.
220
- // That test was redundant wherever it was correct: with a name list this gate
221
- // has already required membership, and without one it has already required
222
- // `sync`, so it could only ever fire in the boolean case it got wrong.
223
- const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
224
- if (!shouldInclude)
225
- continue;
226
- if (effectiveMethod === 'custom' && fetch?.method === 'custom') {
227
- const handlerName = fetch.handler;
228
- const handler = getFetchHandler(handlerName);
229
- if (handler) {
230
- // TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await
231
- // oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above
232
- rowData[fieldname] = await handler(pgClient, rowData, link);
233
- }
234
- continue;
235
- }
236
- // `resolveLinkRenderMode` is the single definition of whether a link expands,
237
- // and this loop was the one caller that never asked it. An `inline` link is a
238
- // picker: the field holds its own id and the client resolves display text
239
- // separately, so expanding it here overwrote that id with the whole target
240
- // record and left the picker with an object it cannot render.
241
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
242
- continue;
243
- const targetMeta = getMeta(link.target);
244
- if (!targetMeta)
245
- continue;
246
- const targetColumns = getSqlColumns(targetMeta);
247
- if (isMany) {
248
- if (!link.backlink)
249
- continue;
250
- const backlinkCol = camelToSnake(link.backlink);
251
- let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
252
- const linkValues = [specId];
253
- // Same reason the list path orders: a capped relation without a fixed order
254
- // returns an arbitrary subset of the children, and a different one each time
255
- // a child row is updated. `truncatedLinks` says the tail was cut; it cannot
256
- // say the head kept changing. Skipped when the target declares no identity —
257
- // there is no stable key to order by, and inventing one would be a guess.
258
- const linkPkMeta = getPkMeta(targetMeta);
259
- if (linkPkMeta) {
260
- sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
261
- }
262
- if (effectiveLimit != null) {
263
- // One row more than the cap, same probe the list path uses: its presence
264
- // is the whole truncation answer and costs no second query.
265
- sql += ` LIMIT $2`;
266
- linkValues.push(effectiveLimit + 1);
267
- }
268
- // TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await
269
- // oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above
270
- const { rows: linked } = await debugSql(pgClient, {
271
- text: sql,
272
- values: linkValues,
273
- });
274
- // A truncated relation that says nothing is how a read-modify-write deletes
275
- // the tail: the client cannot tell 50 rows from all of them, so it writes
276
- // back what it was given. Reported for every source of truncation, the
277
- // author's `fetch.limit` included — that one is just as silent.
278
- if (effectiveLimit != null && linked.length > effectiveLimit) {
279
- truncatedLinks.push(fieldname);
280
- rowData[fieldname] = linked.slice(0, effectiveLimit);
281
- }
282
- else {
283
- rowData[fieldname] = linked;
284
- }
285
- }
286
- else {
287
- // Read from the reserved alias, never the fieldname: an expanding link's FK
288
- // column is deliberately absent from `getSqlColumns`, so the plain read found
289
- // `undefined` on every record and answered `null` — a relation that looked
290
- // permanently empty rather than one nobody had asked the right question for.
291
- const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
292
- if (fkValue == null) {
293
- rowData[fieldname] = null;
294
- continue;
295
- }
296
- // `continue` here would drop the link from the payload, which reads to the
297
- // client as "this record has no such relation" rather than "its target
298
- // cannot be identified".
299
- const targetPkMeta = getPkMeta(targetMeta);
300
- if (!targetPkMeta)
301
- throw unresolvableIdentityError(targetMeta.name);
302
- const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
303
- // TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await
304
- // oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above
305
- const { rows: linked } = await debugSql(pgClient, {
306
- text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
307
- values: [fkValue],
308
- });
309
- rowData[fieldname] = linked[0] ?? null;
310
- }
311
- }
312
- }
313
- // The aliases are a read channel for this loop, not part of the record. Stripped
314
- // unconditionally so a link that was never expanded cannot leak its raw FK into a
315
- // payload that has otherwise always described that relation as a nested object.
316
- for (const { alias } of linkFkAliases)
317
- delete rowData[alias];
318
- // Names in includeNested that don't correspond to any link
319
- const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
320
- results[i] = {
321
- data: rowData,
322
- doctype,
323
- unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
324
- truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
325
- };
326
- }
327
- // After the expansion loop, not before it: a link that expanded has replaced its
328
- // scalar FK with an object, and enrichment skips those. Running first stamped a
329
- // display value beside a relation that no longer had an id to display.
330
- await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
331
- }
332
- return results;
333
- });
334
- },
335
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
336
- return loadOneWithPgClient(executor, object({
337
- doctype: $doctype,
338
- filters: $filters,
339
- orderBy: $orderBy,
340
- limit: $limit,
341
- offset: $offset,
342
- includeTotal: $includeTotal,
343
- }), async (pgClient, specs) => {
344
- return await Promise.all(specs.map(async (spec) => {
345
- const doctype = String(spec.doctype);
346
- const meta = getMeta(doctype);
347
- if (!meta) {
348
- // An unknown doctype answers "no records" rather than erroring, so a caller
349
- // who asked for a total gets 0. Returning null here would make null mean
350
- // two things — "you did not ask" and "I could not say" — and a client
351
- // cannot tell those apart.
352
- return { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null };
353
- }
354
- const knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname));
355
- const columns = getSqlColumns(meta);
356
- const values = [];
357
- // WHERE from filters (parameterised — safe against SQL injection)
358
- const whereClauses = [];
359
- if (spec.filters != null) {
360
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema
361
- for (const [field, value] of Object.entries(spec.filters)) {
362
- if (!knownFields.has(field)) {
363
- throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
364
- }
365
- values.push(value);
366
- whereClauses.push(`"${camelToSnake(field)}" = $${values.length}`);
367
- }
368
- }
369
- const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
370
- // ORDER BY (field name whitelisted — column names cannot be parameterised)
371
- let orderByClause = '';
372
- if (spec.orderBy != null) {
373
- if (typeof spec.orderBy !== 'string')
374
- throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
375
- const orderByStr = spec.orderBy;
376
- const lastUnder = orderByStr.lastIndexOf('_');
377
- if (lastUnder <= 0) {
378
- throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
379
- }
380
- const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
381
- if (dir !== 'ASC' && dir !== 'DESC') {
382
- throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
383
- }
384
- const fieldName = orderByStr.slice(0, lastUnder);
385
- if (!knownFields.has(fieldName)) {
386
- throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
387
- }
388
- orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
389
- }
390
- // A page is only meaningful against a fixed order, and LIMIT/OFFSET without one
391
- // is two independent scans of heap order — an UPDATE between them moves that row
392
- // to the tail, so the row it displaced is never returned and nothing in the
393
- // payload says a record was skipped. The declared identity is the right default
394
- // because it is unique: it gives a total order, which is what makes page 2 start
395
- // exactly where page 1 stopped.
396
- //
397
- // Only when the doctype declares an identity. Without one there is no stable key
398
- // to order by, and inventing one here would be a guess; such a doctype cannot be
399
- // paged stably by any means.
400
- if (orderByClause === '') {
401
- const listPkMeta = getPkMeta(meta);
402
- if (listPkMeta) {
403
- orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
404
- }
405
- }
406
- // LIMIT / OFFSET. A caller that names no limit gets the configured default rather
407
- // than the whole table: omission is how an unbounded scan used to happen, and the
408
- // only guard against it lived in the scaffold's fetch helper, which is neither the
409
- // right layer nor present in a host that wrote its own.
410
- // Grafast passes arguments through as loosely-typed runtime values, so narrow
411
- // before doing arithmetic on this — same reason orderBy is validated above.
412
- if (spec.limit != null && typeof spec.limit !== 'number') {
413
- throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
414
- }
415
- const effectiveLimit = spec.limit ?? defaultRowLimit;
416
- let pagingClause = '';
417
- if (effectiveLimit != null) {
418
- // One more row than asked for. Its presence is the whole `hasMore` answer, and
419
- // it is discarded below — this is why knowing a list is truncated costs no
420
- // second query, where a COUNT(*) would be a full scan on every list read.
421
- values.push(effectiveLimit + 1);
422
- pagingClause += ` LIMIT $${values.length}`;
423
- }
424
- if (spec.offset != null) {
425
- values.push(spec.offset);
426
- pagingClause += ` OFFSET $${values.length}`;
427
- }
428
- const { rows } = await debugSql(pgClient, {
429
- text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
430
- values,
431
- });
432
- // The extra row requested above is a probe, not data. Its presence is what makes
433
- // a capped page distinguishable from a complete table; trim it before anything
434
- // downstream can mistake it for a record.
435
- const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
436
- const data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)];
437
- await enrichLinkDisplayFields(pgClient, meta, data, options.tables, debugSql);
438
- // Total matching the filters, independent of LIMIT/OFFSET, and opt-in.
439
- //
440
- // Explicitly requested rather than inferred from whether `count` was selected:
441
- // this resolver is a Grafast plan step and receives only its arguments, never the
442
- // selection set, and making the plan vary by selection is what Grafast optimises
443
- // against. An argument also puts the cost in the query the client wrote.
444
- let count = null;
445
- if (spec.includeTotal === true) {
446
- const countValues = [];
447
- const countWhere = [];
448
- if (spec.filters != null) {
449
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema
450
- for (const [field, value] of Object.entries(spec.filters)) {
451
- if (!knownFields.has(field))
452
- continue;
453
- countValues.push(value);
454
- countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
455
- }
456
- }
457
- const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : '';
458
- const { rows: countRows } = await debugSql(pgClient, {
459
- text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,
460
- values: countValues,
461
- });
462
- count = parseInt(countRows[0]?.row_count ?? '0', 10);
463
- }
464
- return { data, doctype, hasMore, count };
465
- }));
466
- });
467
- },
468
- },
469
- },
470
- Mutation: {
471
- plans: {
472
- stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
473
- return sideEffectWithPgClient(executor, object({ doctype: $doctype, action: $action, actionArgs: $actionArgs }), async (pgClient, spec) => {
474
- const meta = getMeta(String(spec.doctype));
475
- if (!meta) {
476
- return {
477
- success: false,
478
- data: null,
479
- error: `Unknown doctype: ${spec.doctype}`,
480
- };
481
- }
482
- const actionDef = meta.workflow?.actions?.[spec.action];
483
- if (!actionDef) {
484
- return {
485
- success: false,
486
- data: null,
487
- error: `Unknown action: ${spec.action} on ${spec.doctype}`,
488
- };
489
- }
490
- const table = resolveTableName(meta.name, options.tables);
491
- // Resolved lazily: only a state read or write needs the key column. A
492
- // record-less command reaches its handler on a doctype that declares no
493
- // primary key, which an eager check would refuse for no reason.
494
- const pkColumn = () => {
495
- const pkMeta = getPkMeta(meta);
496
- if (!pkMeta)
497
- throw unresolvableIdentityError(String(spec.doctype));
498
- return camelToSnake(pkMeta.fieldname);
499
- };
500
- // Record envelope: [{ id, data }] — the transition keys off the record id.
501
- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract
502
- const rawArgs = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []);
503
- // An inline link arrives as `{ id, displayText }`; a column takes the id alone.
504
- // Reduced here so no client has to know what storage accepts.
505
- //
506
- // The whole envelope, not just `recordData` below — handlers read `ctx.args`.
507
- // Copied, not mutated: `spec.actionArgs` is the request's own value.
508
- const argList = rawArgs.map(entry => entry?.data ? { ...entry, data: unwrapInlineLinks(meta.fields, entry.data) } : entry);
509
- const recordId = argList[0]?.id;
510
- const recordData = argList[0]?.data ?? {};
511
- // The database author's effect for this action, if one is registered. Keyed
512
- // by the doctype's canonical name so a slug-resolved lookup above cannot
513
- // silently miss it.
514
- const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
515
- // What a data write is allowed to set. Column identifiers come from the
516
- // doctype and never from the request — `args` is an opaque JSON scalar, so
517
- // every key in `data` is browser-supplied — which is what makes it safe to
518
- // build SQL from a patch at all.
519
- //
520
- // The same derivation the read path uses, so what a record exposes is what a
521
- // record accepts. `status` is removed because state is the workflow's to
522
- // move, never the patch's.
523
- const writable = new Map(columnBackedFields(meta.fields)
524
- .filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)
525
- .map(f => [f.fieldname, f]));
526
- // Whether this doctype has a workflow state to read at all. Derived from the
527
- // same declarations, so the guard cannot look for a column the doctype's own
528
- // API surface does not describe.
529
- const declaresState = columnBackedFields(meta.fields).some(f => camelToSnake(f.fieldname) === STATE_COLUMN);
530
- // Reported on the result rather than logged: a dropped key is data the user
531
- // believes was saved, which is the same data-loss signal `truncatedLinks`
532
- // carries for a truncated read.
533
- const droppedFields = [];
534
- const partitionPatch = (patch) => {
535
- const cols = [];
536
- const values = [];
537
- for (const [key, value] of Object.entries(patch)) {
538
- if (!writable.has(key)) {
539
- droppedFields.push(key);
540
- continue;
541
- }
542
- // An expanding link reads back as a nested record while its column
543
- // holds a scalar foreign key, so a read-modify-write hands this loop
544
- // an object bound for a uuid column. The name resolving is not
545
- // enough; the shape has to match a column value too.
546
- if (value !== null && typeof value === 'object') {
547
- droppedFields.push(key);
548
- continue;
549
- }
550
- cols.push(camelToSnake(key));
551
- values.push(value);
552
- }
553
- return { cols, values };
554
- };
555
- // One transaction spans the guard read, the effect and the state write, so an
556
- // action either lands whole or not at all. `withTransaction` issues `begin` at
557
- // the top level and a `savepoint` if something upstream already opened one, so
558
- // nesting is safe rather than something callers must avoid.
559
- //
560
- // Every statement below runs on `tx`, not on the outer client. Work sent to the
561
- // outer client — or to a connection a handler opens itself — is outside this
562
- // transaction and would survive a rollback.
563
- try {
564
- return await pgClient.withTransaction(async (tx) => {
565
- const outcome = await applyGuardedTransition(actionDef, {
566
- readState: async () => {
567
- // No id in the envelope means no record was targeted at all, which is
568
- // the same answer as a lookup that misses: `null`, not `undefined`.
569
- if (recordId == null)
570
- return null;
571
- // Selecting `status` unconditionally made this read fail outright on
572
- // any table without that column — and a self-transition reaches here
573
- // not to read a state but to learn whether the row exists, which is
574
- // what decides create vs. update. So the projection follows the
575
- // doctype: a doctype that declares no state field has none to read,
576
- // and the honest answer for a row it finds is "exists, no state".
577
- // (Measured: 24 of FAB's 35 guarded tables have no `status` column.)
578
- const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
579
- // FOR UPDATE holds the row until this transaction ends, so a second
580
- // action on the same record waits rather than reading the same state
581
- // and acting on it too. Without it the guard is a check-then-act
582
- // race: two concurrent approvals both read PENDING and both proceed.
583
- const { rows } = await debugSql(tx, {
584
- text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
585
- values: [String(recordId)],
586
- });
587
- // No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.
588
- if (rows.length === 0)
589
- return null;
590
- if (!declaresState)
591
- return undefined;
592
- return rows[0][STATE_COLUMN] ?? undefined;
593
- },
594
- writeState: async (nextState) => {
595
- await debugSql(tx, {
596
- text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
597
- values: [nextState, String(recordId)],
598
- });
599
- },
600
- // The upsert, and the only write path for record data. `exists`
601
- // comes from the guard's own read, so no second lookup decides it.
602
- //
603
- // Returns the same projection the read path selects, never
604
- // `RETURNING *`: raw columns come back snake_case, and the client
605
- // resolves identity by the *declared fieldname*. A doctype keyed
606
- // `itemId` would receive `item_id`, find no identity, and file a
607
- // created record nowhere — which is that exact bug, already once
608
- // shipped and patched downstream.
609
- writeData: async (patch, exists) => {
610
- const { cols, values } = partitionPatch(patch);
611
- const returning = getSqlColumns(meta);
612
- if (!exists) {
613
- // Creating is what the *absence* of an id means. An id that was
614
- // dispatched and matched nothing is a record that has gone away
615
- // since the client read it, and treating that as a create mints a
616
- // second row under a new identity while the client believes it
617
- // updated the first — a lost update that reports success.
618
- //
619
- // The dispatcher cannot make this call: it never receives the id,
620
- // deliberately, since identity is the backend's business. So the
621
- // distinction its `readState` contract collapses is restored here,
622
- // where the id is in scope.
623
- if (recordId != null) {
624
- throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", ` +
625
- `which no longer exists. Nothing was created — a record dispatched with an ` +
626
- `identity is an update, and creating one is what dispatching no identity means.`);
627
- }
628
- // No identity is minted here. A declared key present in the
629
- // patch is a natural key the user filled in and passes
630
- // through the whitelist like any other column; absent, the
631
- // column default supplies it. Either way the row states its
632
- // own identity back.
633
- const text = cols.length
634
- ? `INSERT INTO ${table} (${cols.map(c => `"${c}"`).join(', ')}) VALUES (${cols.map((_col, i) => `$${i + 1}`).join(', ')}) RETURNING ${returning}`
635
- : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning}`;
636
- const { rows } = await debugSql(tx, { text, values });
637
- return rows[0] ?? {};
638
- }
639
- // Nothing writable survived the patch. `SET` with no assignments
640
- // is a syntax error, and reporting failure would be wrong — the
641
- // record is fine, it just has no new data. Read it back so the
642
- // client still gets the record, with `droppedFields` saying why
643
- // nothing changed.
644
- if (cols.length === 0) {
645
- const { rows } = await debugSql(tx, {
646
- text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
647
- values: [String(recordId)],
648
- });
649
- return rows[0] ?? {};
650
- }
651
- const assignments = cols.map((c, i) => `"${c}" = $${i + 1}`).join(', ');
652
- const { rows } = await debugSql(tx, {
653
- text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
654
- values: [...values, String(recordId)],
655
- });
656
- return rows[0] ?? {};
657
- },
658
- runEffect: handler
659
- ? (currentState) => handler({
660
- pgClient: tx,
661
- doctype: String(spec.doctype),
662
- action: String(spec.action),
663
- meta,
664
- recordId,
665
- data: recordData,
666
- args: argList,
667
- currentState,
668
- })
669
- : undefined,
670
- },
671
- // The patch a self-transition persists. This adapter never passed it, which
672
- // was moot while it had no `writeData` — nothing consumed it. Wiring the write
673
- // without this argument saves an empty record and reports success.
674
- recordData);
675
- // `applyGuardedTransition` REPORTS failure, it does not throw — a refused
676
- // guard and a handler that blew up both come back as `{ success: false }`.
677
- // Returning that normally would commit the transaction, so a handler that
678
- // wrote three rows and then threw would keep all three. Throwing here is
679
- // what makes the rollback happen; the envelope is carried across so the
680
- // caller still gets `success: false` rather than a GraphQL error.
681
- if (!outcome.success)
682
- throw new ActionRolledBack(outcome);
683
- // A record a write returns is a record, so it carries the links a read
684
- // resolves. Enriching one path and not the other changes a record's
685
- // shape depending on how the client came by it: a link rendered its
686
- // display text until the record was saved, and its raw id from then
687
- // until the next full fetch. Nothing fails — the field just goes wrong.
688
- //
689
- // Runs inside the transaction so the lookup sees the row just written,
690
- // and only on success, since a rolled-back action returns no record.
691
- // A result that is not a record at all — an effect's `{ state }` — has
692
- // no field the doctype declares as an inline link, so it is untouched.
693
- if (outcome.success && outcome.data !== null && typeof outcome.data === 'object') {
694
- // A predicate rather than an assertion: an element that is not an object has
695
- // no field to enrich, so dropping it is the honest answer.
696
- const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === 'object');
697
- await enrichLinkDisplayFields(tx, meta, written, options.tables, debugSql);
698
- }
699
- // Attached here rather than carried through `applyGuardedTransition`:
700
- // which keys a backend can store is a storage question, and the
701
- // dispatcher is deliberately storage-agnostic. A failed action wrote
702
- // nothing, so the list is only meaningful on success.
703
- return droppedFields.length ? { ...outcome, droppedFields } : outcome;
704
- });
705
- }
706
- catch (err) {
707
- if (err instanceof ActionRolledBack)
708
- return err.outcome;
709
- return {
710
- success: false,
711
- data: null,
712
- error: err instanceof Error ? err.message : String(err),
713
- };
714
- }
715
- });
716
- },
717
- },
718
- },
719
- },
720
- };
721
- });
722
- };
723
- // ===========================================================================
724
- // SQL column helpers
725
- // ===========================================================================
726
- /**
727
- * Derive quoted SQL column entries from a flat field array.
728
- * Skips non-scalar fields (kind !== 'field'), `computed` fields
729
- * (no backing DB column), and *expanding* links
730
- * (relations fetched separately, not scalar columns on this table).
731
- */
732
- function collectColumns(fields, links) {
733
- const columns = [];
734
- for (const f of columnBackedFields(fields)) {
735
- // Only an *expanding* link is a relation rather than a column. An inline link (a picker)
736
- // keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the
737
- // shared rule, also used by the client resolver; never re-derive it here.
738
- const link = links.get(f.fieldname);
739
- if (link && resolveLinkRenderMode(link, f.component) !== 'inline')
740
- continue;
741
- const col = camelToSnake(f.fieldname);
742
- columns.push(col !== f.fieldname ? `"${col}" AS "${f.fieldname}"` : `"${f.fieldname}"`);
743
- }
744
- return columns;
745
- }
746
- /**
747
- * Derive a quoted SQL column list from doctype field definitions.
748
- * Applies camelToSnake to each fieldname to get the DB column name, then
749
- * aliases it back to the fieldname so result rows carry API-layer keys.
750
- * Excludes `computed` fields (no backing DB column), Fieldset
751
- * containers (recursing into their children instead), and *expanding* links
752
- * (relations fetched separately). An inline link keeps its FK column here.
753
- *
754
- * Exported for unit testing (not re-exported from the package index).
755
- */
756
- export function getSqlColumns(meta) {
757
- const links = new Map();
758
- if (meta.links) {
759
- for (const [key, link] of Object.entries(meta.links)) {
760
- links.set(link.fieldname ?? key, link);
761
- }
762
- }
763
- return collectColumns(meta.fields, links).join(', ');
764
- }
765
- /**
766
- * Resolve the declared field this doctype's records are looked up by.
767
- *
768
- * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the
769
- * client's record keying name the same field — including the `id` fallback, whose absence here
770
- * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the
771
- * client and refused outright by this adapter, so every fetch answered `null` and looked exactly
772
- * like a record that does not exist.
773
- *
774
- * Returns `undefined` only when the resolved name is not a declared field — a doctype with no
775
- * `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared fields
776
- * only, so the row map would key on a column the SELECT never returned and every lookup would miss
777
- * silently. Callers must say so rather than answer `null`.
778
- *
779
- * Descends into fieldsets, because both halves of the question already do — `getSqlColumns` selects
780
- * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this
781
- * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose
782
- * SELECT carried its own key column had no identity to look that column up by.
783
- */
784
- function getPkMeta(meta) {
785
- const fieldname = getRecordIdField(meta.fields);
786
- return flattenFields(meta.fields).find((f) => f.kind === 'field' && f.fieldname === fieldname);
787
- }
788
- /**
789
- * Assert that every registered action handler names a doctype and an action that exist.
790
- *
791
- * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler
792
- * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.
793
- * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it
794
- * has one, the missing effect is skipped and the state write still reports success. So renaming a
795
- * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.
796
- *
797
- * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a
798
- * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a
799
- * real doctype here and still never fires. It is reported as its own case rather than as "unknown
800
- * doctype", because the repair is different.
801
- *
802
- * Throws rather than warns: there is no legitimate reason to register a handler for an action that
803
- * does not exist, and the alternative is a silent half-executed workflow. Every offender is
804
- * collected so a consumer with several fixes them in one pass.
805
- */
806
- function assertActionHandlersResolve(actionHandlers) {
807
- // Nothing registered, nothing to check.
808
- const registered = Object.entries(actionHandlers);
809
- if (registered.length === 0)
810
- return;
811
- // An empty registry cannot tell "this key is stale" from "doctypes have not loaded yet" — a
812
- // host is free to build the schema before its loader runs. Warn on that ambiguity rather than
813
- // failing a boot that is merely early.
814
- if (getAllMeta().length === 0) {
815
- // oxlint-disable-next-line no-console
816
- console.warn('[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +
817
- '`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +
818
- 'have stale handler keys reported.');
819
- return;
820
- }
821
- const orphans = [];
822
- for (const [doctypeKey, handlers] of registered) {
823
- const meta = getMeta(doctypeKey);
824
- if (!meta) {
825
- orphans.push(`"${doctypeKey}": no doctype by that name is registered`);
826
- continue;
827
- }
828
- if (meta.name !== doctypeKey) {
829
- orphans.push(`"${doctypeKey}": matches the doctype named "${meta.name}" by slug, but handlers are looked up by name — key it "${meta.name}"`);
830
- continue;
831
- }
832
- const actions = meta.workflow?.actions ?? {};
833
- for (const actionKey of Object.keys(handlers)) {
834
- if (!(actionKey in actions)) {
835
- orphans.push(`"${doctypeKey}.${actionKey}": the doctype declares no action by that key`);
836
- }
837
- }
838
- }
839
- if (orphans.length > 0) {
840
- throw new Error(`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +
841
- `cannot be reached and would never run:\n ${orphans.join('\n ')}`);
842
- }
843
- }
844
- /**
845
- * Refuse a doctype set whose links or `inherits` name a doctype nobody registered.
846
- *
847
- * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed
848
- * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response
849
- * with no error. On the wire that is indistinguishable from "this record has no such relation", and
850
- * a typo in a target reads as a legitimately empty link forever.
851
- *
852
- * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not
853
- * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.
854
- *
855
- * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns
856
- * because a registered handler map is evidence the host meant to be checked; here there is no such
857
- * evidence, so warning would fire on every host that loads doctypes after building its schema —
858
- * and an advisory that fires on a correct setup is worse than none. An empty registry simply
859
- * reports nothing, because the loop has nothing to walk.
860
- */
861
- function assertReferencesResolve() {
862
- const broken = validateReferences();
863
- if (broken.length === 0)
864
- return;
865
- throw new Error(`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +
866
- `cannot be resolved and would silently drop the relation:\n ` +
867
- broken.map(e => `${e.path.join('.')}: ${e.message}`).join('\n '));
868
- }
869
- /**
870
- * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype
871
- * and both repairs. Shared so the three lookup sites report one diagnosis.
872
- */
873
- function unresolvableIdentityError(doctype) {
874
- return new Error(`Doctype "${doctype}" has no identity field: it declares no field with \`primaryKey: true\` ` +
875
- `and no field named \`id\`. Declare one of the two — records cannot be fetched or acted on until then.`);
876
- }
877
- /**
878
- * Resolve the PostgreSQL FROM clause target for a doctype.
879
- * Uses the `tables` override map first; falls back to camelToSnake(name).
880
- * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
881
- * Values must be bare identifiers or schema.table pairs — not SQL fragments.
882
- */