@stonecrop/graphql-middleware 0.17.0 → 0.18.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.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Recursively flatten Fieldset containers into a flat array of non-container fields.
3
+ * Fieldset entries are replaced by their children; all other fields pass through.
4
+ *
5
+ * A fieldset is a layout grouping, not a scope: every field inside one is a field of the doctype,
6
+ * with a column of its own and a name a link can bind to. Anything asking "what does this doctype
7
+ * declare" must therefore descend, and the two ways to get that wrong point opposite ways — the
8
+ * SELECT builder would omit real columns, while a validator would report a working declaration as
9
+ * broken.
10
+ *
11
+ * Lives here rather than beside either caller because it now has three of them across two modules
12
+ * (`getSqlColumns` and `knownFields` in the plugin, `validateReferences` in the registry), and a
13
+ * second copy is how the plugin and the registry would come to disagree about what a doctype
14
+ * declares. Internal — not re-exported from the package index.
15
+ */
16
+ export function flattenFields(fields) {
17
+ const result = [];
18
+ for (const f of fields) {
19
+ if (f.kind === 'fieldset') {
20
+ result.push(...flattenFields(f.schema));
21
+ }
22
+ else {
23
+ result.push(f);
24
+ }
25
+ }
26
+ return result;
27
+ }
28
+ /**
29
+ * The fields that have a database column of their own — the one definition of that question.
30
+ *
31
+ * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is
32
+ * declared precisely to state it has no column, and a container (a table field) is a relation
33
+ * rather than a value. Everything else names a column.
34
+ *
35
+ * This is deliberately **not** the same question as "does this column belong in a record payload".
36
+ * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`
37
+ * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the
38
+ * two is how the read path came to drop the very column its expansion needed. Callers wanting the
39
+ * payload projection filter this further by render mode; callers asking whether a column exists —
40
+ * link validation, and the write path deciding what it may set — want it unfiltered.
41
+ *
42
+ * Extracted because the rule had grown three statements across two modules, one of them a comment
43
+ * reading "mirrors `collectColumns`". A rule that has to be mirrored by hand is one edit away from
44
+ * the read path and the validator disagreeing about what a doctype declares.
45
+ */
46
+ export function columnBackedFields(fields) {
47
+ return flattenFields(fields).filter((f) => f.kind === 'field' && !f.computed);
48
+ }
@@ -118,18 +118,26 @@ export interface StonecropPluginOptions {
118
118
  */
119
119
  actionHandlers?: Record<string, Record<string, ActionHandler>>;
120
120
  /**
121
- * Row cap applied to `stonecropRecords` when the caller requests no `limit`. Defaults to 200.
121
+ * Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests
122
+ * no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults
123
+ * to 200.
122
124
  *
123
125
  * A row cap is a statement about what this database can afford to serve, so it belongs to
124
126
  * whoever owns the database — not to a doctype (which describes the API surface, not the
125
127
  * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
126
128
  * free to ask for less; they cannot ask for an unbounded scan by omission.
127
129
  *
128
- * `hasMore` reports whether the cap truncated the result, so a capped page is always
129
- * distinguishable from a complete one without asking for a count.
130
+ * One number covers both reads because a link *is* a list, fetched a different way. It used to
131
+ * be capped at a hard-coded 50 that no option could reach, which is how an operator watching a
132
+ * slow query found there was no knob to turn.
130
133
  *
131
- * Set to `null` for no default cap. That is the pre-0.17 behaviour and it means an unqualified
132
- * list query returns the whole table.
134
+ * Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a
135
+ * partial answer is distinguishable from a complete one without asking for a count. That
136
+ * matters more for a link than for a list: a link cannot be paged, so a client that writes
137
+ * back a truncated relation deletes the rows it was never sent.
138
+ *
139
+ * Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an
140
+ * unqualified list query returns the whole table and a link returns the whole relation.
133
141
  */
134
142
  defaultRecordLimit?: number | null;
135
143
  }
@@ -1 +1 @@
1
- {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,WAAW,EAKX,MAAM,mBAAmB,CAAA;AAG1B,OAAO,KAAK,EAAE,QAAQ,EAAc,M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;;;;;;;OAqBG;IACH,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAClC;AAmCD;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MAgqB3F,CAAA;AA0BD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAQvD"}
@@ -2,6 +2,7 @@ import { camelToSnake, getRecordIdField, pascalToSnake, resolveLinkRenderMode }
2
2
  import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
3
3
  import { constant, lambda, object } from 'postgraphile/grafast';
4
4
  import { extendSchema } from 'postgraphile/utils';
5
+ import { columnBackedFields, flattenFields } from '../fields';
5
6
  import { getFetchHandler } from '../registry/fetchHandlers';
6
7
  import { getMeta, getAllMeta, validateReferences } from '../registry/doctypes';
7
8
  import { applyGuardedTransition } from '../dispatch/transition';
@@ -22,6 +23,22 @@ class ActionRolledBack extends Error {
22
23
  this.name = 'ActionRolledBack';
23
24
  }
24
25
  }
26
+ /**
27
+ * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
28
+ * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getSqlColumns`
29
+ * omits its FK column by design — but the expansion needs the value to find the target. Aliasing
30
+ * keeps that need from changing the payload: every alias is stripped before the record is returned.
31
+ */
32
+ const LINK_FK_ALIAS = '__stonecropLinkFk_';
33
+ /**
34
+ * The column this adapter keeps a record's workflow state in.
35
+ *
36
+ * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,
37
+ * the transition's write, and the data write that must refuse to touch it. A patch that could set
38
+ * this column would let any client walk past `allowedStates` by writing the very value the guard
39
+ * reads.
40
+ */
41
+ const STATE_COLUMN = 'status';
25
42
  /**
26
43
  * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
27
44
  *
@@ -45,6 +62,10 @@ export const createStonecropPlugin = (options = {}) => {
45
62
  return pgClient.query(query);
46
63
  }
47
64
  : (pgClient, query) => pgClient.query(query);
65
+ // Resolved once, for both read paths. `undefined` means "not configured" and `null` means
66
+ // "configured off", which is a distinction `??` cannot make — and the two paths disagreeing
67
+ // about it is exactly how a link came to be capped by a different number than a list.
68
+ const defaultRowLimit = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit;
48
69
  return extendSchema(build => {
49
70
  // Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
50
71
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type
@@ -98,11 +119,37 @@ export const createStonecropPlugin = (options = {}) => {
98
119
  const pkColumn = camelToSnake(pkMeta.fieldname);
99
120
  const columns = getSqlColumns(meta);
100
121
  const ids = indices.map(i => String(specs[i].id));
122
+ // Resolved once per doctype: how each link renders, and which foreign keys the
123
+ // SELECT must carry for the expansion below to work at all.
124
+ //
125
+ // `resolveLinkRenderMode` needs the linked field's own component, so the fields
126
+ // are indexed by name — flattened, because a link's field may sit inside a
127
+ // fieldset and `getSqlColumns` already descends to select it.
128
+ const fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]));
129
+ const linkFkAliases = [];
130
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
131
+ // Many-side links find their rows by a column on the *target*; only a one-side
132
+ // link reads a foreign key off this row.
133
+ if (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne')
134
+ continue;
135
+ const fieldname = link.fieldname ?? linkName;
136
+ // An inline link keeps its FK as a scalar, so `getSqlColumns` already selected
137
+ // it under its own name and no alias is needed.
138
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
139
+ continue;
140
+ linkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` });
141
+ }
142
+ const selectList = [
143
+ columns,
144
+ ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`),
145
+ ]
146
+ .filter(Boolean)
147
+ .join(', ');
101
148
  // TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;
102
149
  // requires refactoring the grouped-by-doctype loop to collect promises before resolving results
103
150
  // oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above
104
151
  const { rows } = await debugSql(pgClient, {
105
- text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
152
+ text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
106
153
  values: [ids],
107
154
  });
108
155
  // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
@@ -130,6 +177,9 @@ export const createStonecropPlugin = (options = {}) => {
130
177
  continue;
131
178
  }
132
179
  const rowData = { ...row };
180
+ // Per record, not per doctype: two records of one doctype can differ in whether
181
+ // a relation overflowed, and a shared list would report the wrong one truncated.
182
+ const truncatedLinks = [];
133
183
  const recordOptions = (specs[i].options ?? {});
134
184
  const includeAll = recordOptions.includeNested === true;
135
185
  const includeSet = Array.isArray(recordOptions.includeNested)
@@ -138,10 +188,30 @@ export const createStonecropPlugin = (options = {}) => {
138
188
  // FetchStrategy dispatch over link declarations
139
189
  if (meta.links) {
140
190
  for (const [linkName, link] of Object.entries(meta.links)) {
191
+ // The payload key is the *resolved* fieldname, not the map key: the client
192
+ // binds a link to the field named `link.fieldname ?? key` and reads the
193
+ // nested data off that field, so writing under the bare key put the result
194
+ // somewhere nothing looks whenever a declaration named its own `fieldname`.
195
+ // Identical for every declaration that omits `fieldname`, which is all of them
196
+ // in this repo — hence latent until now.
197
+ const fieldname = link.fieldname ?? linkName;
141
198
  const fetch = link.fetch;
142
199
  const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
143
200
  const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
144
- const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
201
+ // Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only
202
+ // `SyncFetch` carries a `limit` — and the server default used to hang off its
203
+ // `else`, so declaring the method a many-side link already defaults to removed
204
+ // the cap entirely. "Did the author write a limit?" and "did the author write
205
+ // the word sync?" are now asked separately.
206
+ const declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined;
207
+ const effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined;
208
+ // The one gate. It used to be followed by a second test that re-asked the
209
+ // same question using only `includeSet` — `null` for the boolean form — so
210
+ // `includeNested: true` admitted every link here and then silently dropped
211
+ // each non-`sync` one, handing back a partial record with no way to tell.
212
+ // That test was redundant wherever it was correct: with a name list this gate
213
+ // has already required membership, and without one it has already required
214
+ // `sync`, so it could only ever fire in the boolean case it got wrong.
145
215
  const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
146
216
  if (!shouldInclude)
147
217
  continue;
@@ -151,11 +221,16 @@ export const createStonecropPlugin = (options = {}) => {
151
221
  if (handler) {
152
222
  // TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await
153
223
  // oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above
154
- rowData[linkName] = await handler(pgClient, rowData, link);
224
+ rowData[fieldname] = await handler(pgClient, rowData, link);
155
225
  }
156
226
  continue;
157
227
  }
158
- if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
228
+ // `resolveLinkRenderMode` is the single definition of whether a link expands,
229
+ // and this loop was the one caller that never asked it. An `inline` link is a
230
+ // picker: the field holds its own id and the client resolves display text
231
+ // separately, so expanding it here overwrote that id with the whole target
232
+ // record and left the picker with an object it cannot render.
233
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline')
159
234
  continue;
160
235
  const targetMeta = getMeta(link.target);
161
236
  if (!targetMeta)
@@ -168,8 +243,10 @@ export const createStonecropPlugin = (options = {}) => {
168
243
  let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
169
244
  const linkValues = [specId];
170
245
  if (effectiveLimit != null) {
246
+ // One row more than the cap, same probe the list path uses: its presence
247
+ // is the whole truncation answer and costs no second query.
171
248
  sql += ` LIMIT $2`;
172
- linkValues.push(effectiveLimit);
249
+ linkValues.push(effectiveLimit + 1);
173
250
  }
174
251
  // TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await
175
252
  // oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above
@@ -177,14 +254,26 @@ export const createStonecropPlugin = (options = {}) => {
177
254
  text: sql,
178
255
  values: linkValues,
179
256
  });
180
- rowData[linkName] = linked;
257
+ // A truncated relation that says nothing is how a read-modify-write deletes
258
+ // the tail: the client cannot tell 50 rows from all of them, so it writes
259
+ // back what it was given. Reported for every source of truncation, the
260
+ // author's `fetch.limit` included — that one is just as silent.
261
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
262
+ truncatedLinks.push(fieldname);
263
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
264
+ }
265
+ else {
266
+ rowData[fieldname] = linked;
267
+ }
181
268
  }
182
269
  else {
183
- if (!link.fieldname)
184
- continue;
185
- const fkValue = rowData[link.fieldname];
270
+ // Read from the reserved alias, never the fieldname: an expanding link's FK
271
+ // column is deliberately absent from `getSqlColumns`, so the plain read found
272
+ // `undefined` on every record and answered `null` — a relation that looked
273
+ // permanently empty rather than one nobody had asked the right question for.
274
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
186
275
  if (fkValue == null) {
187
- rowData[linkName] = null;
276
+ rowData[fieldname] = null;
188
277
  continue;
189
278
  }
190
279
  // `continue` here would drop the link from the payload, which reads to the
@@ -200,16 +289,22 @@ export const createStonecropPlugin = (options = {}) => {
200
289
  text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
201
290
  values: [fkValue],
202
291
  });
203
- rowData[linkName] = linked[0] ?? null;
292
+ rowData[fieldname] = linked[0] ?? null;
204
293
  }
205
294
  }
206
295
  }
296
+ // The aliases are a read channel for this loop, not part of the record. Stripped
297
+ // unconditionally so a link that was never expanded cannot leak its raw FK into a
298
+ // payload that has otherwise always described that relation as a nested object.
299
+ for (const { alias } of linkFkAliases)
300
+ delete rowData[alias];
207
301
  // Names in includeNested that don't correspond to any link
208
302
  const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
209
303
  results[i] = {
210
304
  data: rowData,
211
305
  doctype,
212
306
  unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
307
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,
213
308
  };
214
309
  }
215
310
  }
@@ -280,7 +375,7 @@ export const createStonecropPlugin = (options = {}) => {
280
375
  if (spec.limit != null && typeof spec.limit !== 'number') {
281
376
  throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
282
377
  }
283
- const effectiveLimit = spec.limit ?? (options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit);
378
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
284
379
  let pagingClause = '';
285
380
  if (effectiveLimit != null) {
286
381
  // One more row than asked for. Its presence is the whole `hasMore` answer, and
@@ -373,6 +468,46 @@ export const createStonecropPlugin = (options = {}) => {
373
468
  // by the doctype's canonical name so a slug-resolved lookup above cannot
374
469
  // silently miss it.
375
470
  const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
471
+ // What a data write is allowed to set. Column identifiers come from the
472
+ // doctype and never from the request — `args` is an opaque JSON scalar, so
473
+ // every key in `data` is browser-supplied — which is what makes it safe to
474
+ // build SQL from a patch at all.
475
+ //
476
+ // The same derivation the read path uses, so what a record exposes is what a
477
+ // record accepts. `status` is removed because state is the workflow's to
478
+ // move, never the patch's.
479
+ const writable = new Map(columnBackedFields(meta.fields)
480
+ .filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)
481
+ .map(f => [f.fieldname, f]));
482
+ // Whether this doctype has a workflow state to read at all. Derived from the
483
+ // same declarations, so the guard cannot look for a column the doctype's own
484
+ // API surface does not describe.
485
+ const declaresState = columnBackedFields(meta.fields).some(f => camelToSnake(f.fieldname) === STATE_COLUMN);
486
+ // Reported on the result rather than logged: a dropped key is data the user
487
+ // believes was saved, which is the same data-loss signal `truncatedLinks`
488
+ // carries for a truncated read.
489
+ const droppedFields = [];
490
+ const partitionPatch = (patch) => {
491
+ const cols = [];
492
+ const values = [];
493
+ for (const [key, value] of Object.entries(patch)) {
494
+ if (!writable.has(key)) {
495
+ droppedFields.push(key);
496
+ continue;
497
+ }
498
+ // An expanding link reads back as a nested record while its column
499
+ // holds a scalar foreign key, so a read-modify-write hands this loop
500
+ // an object bound for a uuid column. The name resolving is not
501
+ // enough; the shape has to match a column value too.
502
+ if (value !== null && typeof value === 'object') {
503
+ droppedFields.push(key);
504
+ continue;
505
+ }
506
+ cols.push(camelToSnake(key));
507
+ values.push(value);
508
+ }
509
+ return { cols, values };
510
+ };
376
511
  // One transaction spans the guard read, the effect and the state write, so an
377
512
  // action either lands whole or not at all. `withTransaction` issues `begin` at
378
513
  // the top level and a `savepoint` if something upstream already opened one, so
@@ -389,25 +524,93 @@ export const createStonecropPlugin = (options = {}) => {
389
524
  // the same answer as a lookup that misses: `null`, not `undefined`.
390
525
  if (recordId == null)
391
526
  return null;
527
+ // Selecting `status` unconditionally made this read fail outright on
528
+ // any table without that column — and a self-transition reaches here
529
+ // not to read a state but to learn whether the row exists, which is
530
+ // what decides create vs. update. So the projection follows the
531
+ // doctype: a doctype that declares no state field has none to read,
532
+ // and the honest answer for a row it finds is "exists, no state".
533
+ // (Measured: 24 of FAB's 35 guarded tables have no `status` column.)
534
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
392
535
  // FOR UPDATE holds the row until this transaction ends, so a second
393
536
  // action on the same record waits rather than reading the same state
394
537
  // and acting on it too. Without it the guard is a check-then-act
395
538
  // race: two concurrent approvals both read PENDING and both proceed.
396
539
  const { rows } = await debugSql(tx, {
397
- text: `SELECT "status" FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
540
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
398
541
  values: [String(recordId)],
399
542
  });
400
543
  // No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.
401
544
  if (rows.length === 0)
402
545
  return null;
403
- return rows[0].status ?? undefined;
546
+ if (!declaresState)
547
+ return undefined;
548
+ return rows[0][STATE_COLUMN] ?? undefined;
404
549
  },
405
550
  writeState: async (nextState) => {
406
551
  await debugSql(tx, {
407
- text: `UPDATE ${table} SET "status" = $1 WHERE "${pkColumn()}"::text = $2`,
552
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
408
553
  values: [nextState, String(recordId)],
409
554
  });
410
555
  },
556
+ // The upsert, and the only write path for record data. `exists`
557
+ // comes from the guard's own read, so no second lookup decides it.
558
+ //
559
+ // Returns the same projection the read path selects, never
560
+ // `RETURNING *`: raw columns come back snake_case, and the client
561
+ // resolves identity by the *declared fieldname*. A doctype keyed
562
+ // `itemId` would receive `item_id`, find no identity, and file a
563
+ // created record nowhere — which is that exact bug, already once
564
+ // shipped and patched downstream.
565
+ writeData: async (patch, exists) => {
566
+ const { cols, values } = partitionPatch(patch);
567
+ const returning = getSqlColumns(meta);
568
+ if (!exists) {
569
+ // Creating is what the *absence* of an id means. An id that was
570
+ // dispatched and matched nothing is a record that has gone away
571
+ // since the client read it, and treating that as a create mints a
572
+ // second row under a new identity while the client believes it
573
+ // updated the first — a lost update that reports success.
574
+ //
575
+ // The dispatcher cannot make this call: it never receives the id,
576
+ // deliberately, since identity is the backend's business. So the
577
+ // distinction its `readState` contract collapses is restored here,
578
+ // where the id is in scope.
579
+ if (recordId != null) {
580
+ throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", ` +
581
+ `which no longer exists. Nothing was created — a record dispatched with an ` +
582
+ `identity is an update, and creating one is what dispatching no identity means.`);
583
+ }
584
+ // No identity is minted here. A declared key present in the
585
+ // patch is a natural key the user filled in and passes
586
+ // through the whitelist like any other column; absent, the
587
+ // column default supplies it. Either way the row states its
588
+ // own identity back.
589
+ const text = cols.length
590
+ ? `INSERT INTO ${table} (${cols.map(c => `"${c}"`).join(', ')}) VALUES (${cols.map((_col, i) => `$${i + 1}`).join(', ')}) RETURNING ${returning}`
591
+ : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning}`;
592
+ const { rows } = await debugSql(tx, { text, values });
593
+ return rows[0] ?? {};
594
+ }
595
+ // Nothing writable survived the patch. `SET` with no assignments
596
+ // is a syntax error, and reporting failure would be wrong — the
597
+ // record is fine, it just has no new data. Read it back so the
598
+ // client still gets the record, with `droppedFields` saying why
599
+ // nothing changed.
600
+ if (cols.length === 0) {
601
+ const { rows } = await debugSql(tx, {
602
+ text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
603
+ values: [String(recordId)],
604
+ });
605
+ return rows[0] ?? {};
606
+ }
607
+ const assignments = cols.map((c, i) => `"${c}" = $${i + 1}`).join(', ');
608
+ const { rows } = await debugSql(tx, {
609
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
610
+ values: [...values, String(recordId)],
611
+ });
612
+ return rows[0] ?? {};
613
+ },
411
614
  runEffect: handler
412
615
  ? (currentState) => handler({
413
616
  pgClient: tx,
@@ -420,7 +623,11 @@ export const createStonecropPlugin = (options = {}) => {
420
623
  currentState,
421
624
  })
422
625
  : undefined,
423
- });
626
+ },
627
+ // The patch a self-transition persists. This adapter never passed it, which
628
+ // was moot while it had no `writeData` — nothing consumed it. Wiring the write
629
+ // without this argument saves an empty record and reports success.
630
+ recordData);
424
631
  // `applyGuardedTransition` REPORTS failure, it does not throw — a refused
425
632
  // guard and a handler that blew up both come back as `{ success: false }`.
426
633
  // Returning that normally would commit the transaction, so a handler that
@@ -429,7 +636,11 @@ export const createStonecropPlugin = (options = {}) => {
429
636
  // caller still gets `success: false` rather than a GraphQL error.
430
637
  if (!outcome.success)
431
638
  throw new ActionRolledBack(outcome);
432
- return outcome;
639
+ // Attached here rather than carried through `applyGuardedTransition`:
640
+ // which keys a backend can store is a storage question, and the
641
+ // dispatcher is deliberately storage-agnostic. A failed action wrote
642
+ // nothing, so the list is only meaningful on success.
643
+ return droppedFields.length ? { ...outcome, droppedFields } : outcome;
433
644
  });
434
645
  }
435
646
  catch (err) {
@@ -452,23 +663,6 @@ export const createStonecropPlugin = (options = {}) => {
452
663
  // ===========================================================================
453
664
  // SQL column helpers
454
665
  // ===========================================================================
455
- /**
456
- * Recursively flatten Fieldset containers into a flat array of non-container fields.
457
- * Fieldset entries are replaced by their children; all other fields pass through.
458
- * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).
459
- */
460
- function flattenFields(fields) {
461
- const result = [];
462
- for (const f of fields) {
463
- if (f.kind === 'fieldset') {
464
- result.push(...flattenFields(f.schema));
465
- }
466
- else {
467
- result.push(f);
468
- }
469
- }
470
- return result;
471
- }
472
666
  /**
473
667
  * Derive quoted SQL column entries from a flat field array.
474
668
  * Skips non-scalar fields (kind !== 'field'), `computed` fields
@@ -477,12 +671,7 @@ function flattenFields(fields) {
477
671
  */
478
672
  function collectColumns(fields, links) {
479
673
  const columns = [];
480
- for (const f of flattenFields(fields)) {
481
- if (f.kind !== 'field')
482
- continue;
483
- // A computed field has no backing DB column.
484
- if (f.computed)
485
- continue;
674
+ for (const f of columnBackedFields(fields)) {
486
675
  // Only an *expanding* link is a relation rather than a column. An inline link (a picker)
487
676
  // keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the
488
677
  // shared rule, also used by the client resolver; never re-derive it here.
@@ -61,7 +61,8 @@ export declare function hasMeta(name: string): boolean;
61
61
  */
62
62
  export declare function clearRegistry(): void;
63
63
  /**
64
- * Validate cross-doctype references (link targets, `inherits`) against what is loaded.
64
+ * Validate doctype references — link targets, `inherits`, and each link's binding — against what
65
+ * is loaded.
65
66
  *
66
67
  * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by
67
68
  * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as
@@ -74,6 +75,16 @@ export declare function clearRegistry(): void;
74
75
  * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the
75
76
  * permissive direction.
76
77
  *
78
+ * The **binding** checks are the same defect class as an unresolvable target, one step further in:
79
+ * a link whose target resolves can still name no way to reach the rows, and the reader's answer for
80
+ * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely
81
+ * empty. Both halves of a declaration are `.optional()` in the schema because which one is required
82
+ * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.
83
+ *
84
+ * Only what the runtime actually consults is required. A `backlink` naming a column the target
85
+ * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;
86
+ * the check exists for the silent cases, not to restate the database's own errors.
87
+ *
77
88
  * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that
78
89
  * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only
79
90
  * meaningful after this module's own loaders have run.
@@ -1 +1 @@
1
- {"version":3,"file":"doctypes.d.ts","sourceRoot":"","sources":["../../../src/registry/doctypes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAIrE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;IAE/C,4DAA4D;aAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;aACtB,MAAM,EAAE,eAAe,EAAE;;IAHzC,4DAA4D;IAC5C,IAAI,EAAE,MAAM;IAC5B,sCAAsC;IACtB,MAAM,EAAE,eAAe,EAAE;CAM1C;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IACnC,2DAA2D;IAC3D,eAAe,CAAC,EAAE,OA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