@stonecrop/graphql-middleware 0.16.6 → 0.17.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 CHANGED
@@ -135,7 +135,7 @@ Fields with `computed: true` have no backing database column and are excluded fr
135
135
 
136
136
  ## Actions
137
137
 
138
- Actions are declared per doctype in `workflow.actions` — there is no separate handler registry. Each action names the states it may run from (`allowedStates`) and the state the record moves to (`nextState`):
138
+ Actions are declared per doctype in `workflow.actions`. Each action names the states it may run from (`allowedStates`) and the state the record moves to (`nextState`):
139
139
 
140
140
  ```json
141
141
  "workflow": {
@@ -147,7 +147,19 @@ Actions are declared per doctype in `workflow.actions` — there is no separate
147
147
  }
148
148
  ```
149
149
 
150
- 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`. Actions with no `nextState` (stateless commands) and self-transitions have no state target and are rejected by this backend rather than silently succeeding.
150
+ 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`. Self-transitions (`selfTransition: true`) have no state target and no data-write path on this backend, so they are rejected rather than silently succeeding.
151
+
152
+ 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.
153
+
154
+ ### Creating a record
155
+
156
+ There is no create mutation, no create action, and no separate create write. **Saving a record that does not exist creates it**, because "persist this record's data" is one request whether or not the row is there yet. `GuardedTransitionIO.writeData` is an upsert: it receives an `exists` flag the dispatcher already knows, having read the record's state to run the guard. A backend that omits `writeData` declines both saving and creating, which is the Postgres adapter's position today; the two nuxt hosts implement it.
157
+
158
+ `allowedStates` is deliberately not consulted on creation — it constrains movement between states, and a record being created is not in one. Its initial state is the backend's to set. Only a self-transition creates: a `nextState` transition against a missing record is a bad id, not a request to create one.
159
+
160
+ Identity belongs to `writeData`, not the dispatcher. Read the declared `primaryKey` out of the submitted data for a natural-keyed doctype — that value is a field the user filled in — and mint one only when the doctype is surrogate-keyed. The New Record flow dispatches with **no** `id` in the envelope, because an unsaved record has no identity to send; the created record comes back carrying the one the backend assigned.
161
+
162
+ A `writeData` that only knows how to patch will match no row and return nothing. The dispatcher treats an empty return on the create path as exactly that and fails loudly, rather than letting a save that stored nothing report success.
151
163
 
152
164
  ## Custom fetch handlers
153
165
 
@@ -7,27 +7,99 @@ import type { PgClient } from '@dataplan/pg';
7
7
  import { ValidationError } from '@stonecrop/schema';
8
8
 
9
9
  /**
10
- * Apply a workflow action's state transition on the server, enforcing `allowedStates`.
10
+ * A server-side effect for one doctype action, supplied by whoever owns the database.
11
+ *
12
+ * Throwing rejects the action and no state is written. Returning the updated record makes it the
13
+ * client writeback payload; returning `undefined` leaves the doctype's own outcome to decide.
14
+ *
15
+ * The return value is passed through verbatim as `StonecropActionResult.data`, so it must be
16
+ * API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and
17
+ * ADR 0007.
18
+ * @public
19
+ */
20
+ export declare type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>;
21
+
22
+ /**
23
+ * Everything a server-side action handler is given when `stonecropAction` dispatches to it.
24
+ *
25
+ * A context object rather than positional parameters so the set can grow without breaking
26
+ * registered handlers — the adapters that supply these live in consumer repositories.
27
+ * @public
28
+ */
29
+ export declare interface ActionHandlerContext {
30
+ /**
31
+ * Active database client for the current request. **It is inside the action's transaction.**
32
+ *
33
+ * The guard read, this handler, and the state write all run on this client inside one
34
+ * transaction, so the action is atomic: throw, and everything this handler wrote is rolled
35
+ * back along with the state change. Returning normally commits the lot.
36
+ *
37
+ * Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would
38
+ * close the action's transaction early, committing work the guard may still reject. If you
39
+ * need to undo part of your own work without failing the action, use a `SAVEPOINT`.
40
+ *
41
+ * Work sent to a *different* connection is outside all of this and will not be rolled back —
42
+ * so use this client rather than opening one of your own.
43
+ *
44
+ * Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's
45
+ * own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that
46
+ * returns raw rows therefore leaks snake_case keys to the client. Alias in SQL
47
+ * (`"display_name" AS "displayName"`) or convert with `snakeToCamel` from `@stonecrop/schema`.
48
+ */
49
+ pgClient: PgClient;
50
+ /** The doctype the action was dispatched against, as the client sent it. */
51
+ doctype: string;
52
+ /** The action's key in `workflow.actions` — the same string the handler was registered under. */
53
+ action: string;
54
+ /** The resolved doctype metadata, for field names, the primary key, and the workflow. */
55
+ meta: DoctypeMeta;
56
+ /** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */
57
+ recordId?: string | number;
58
+ /**
59
+ * The record field data the client sent (`args[0].data`).
60
+ *
61
+ * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has
62
+ * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist
63
+ * the fields the action is allowed to touch.
64
+ */
65
+ data: Record<string, unknown>;
66
+ /** The full argument envelope, for the actions that need more than the first record. */
67
+ args: unknown[];
68
+ /** The state the guard read, or `undefined` when nothing about the action required reading it. */
69
+ currentState?: string;
70
+ }
71
+
72
+ /**
73
+ * Apply a workflow action on the server, enforcing `allowedStates`.
11
74
  *
12
75
  * The server owns the transition: it reads the record's authoritative current state,
13
- * rejects the action when `isActionAllowedInState` denies it, then writes `nextState`
14
- * verbatim. Storage access is injected via `io` so this one guard serves every backend
15
- * and can never disagree with the frontend's `getAvailableTransitions`, which shares the
16
- * same predicate.
76
+ * rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
77
+ * Storage access is injected via `io` so this one guard serves every backend and can never
78
+ * disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
79
+ *
80
+ * **The doctype decides whether an action may run and what state results; the adapter decides
81
+ * what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the
82
+ * doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
83
+ * owns the database. Neither names the other: an action never carries a handler name, and a
84
+ * handler never overrides the guard.
17
85
  *
18
- * There are three action shapes this guard distinguishes:
86
+ * There are four action shapes this distinguishes:
19
87
  * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
20
88
  * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
21
89
  * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
22
- * A backend without a data-write path rejects it loudly instead of dropping it silently.
23
- * - Anything else with no `nextState` and no `selfTransition` flag is a genuine authoring mistake (or a
24
- * stateless side-effect command whose server handler is not wired — the intended `callHandler` primitive
25
- * is still unimplemented): it fails loudly before touching the backend rather than reporting a false success.
90
+ * When the target record does not exist the same write creates it — saving a record is one
91
+ * request whether or not the row is there yet, so there is no separate create action, no create
92
+ * mutation, and no second write path for it.
93
+ * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
94
+ * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
95
+ * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
96
+ * authoring mistake or a command whose handler was never wired. It fails loudly before touching
97
+ * the backend rather than reporting a false success.
26
98
  *
27
99
  * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
28
- * @param io - Backend read/write closures
100
+ * @param io - Backend read/write closures, plus the optional adapter-owned effect
29
101
  * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
30
- * @returns Action result envelope — the resulting `data.state` for a transition, the full record for a self-transition
102
+ * @returns Action result envelope — the freshest record the backend produced, or the resulting state
31
103
  * @public
32
104
  */
33
105
  export declare function applyGuardedTransition(actionDef: {
@@ -186,21 +258,65 @@ export declare function getMeta(name: string): DoctypeMeta | undefined;
186
258
  /**
187
259
  * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.
188
260
  * The same guard runs whether the record lives in Postgres, a mock executor, or an
189
- * in-memory Map — only these two closures change per backend.
261
+ * in-memory Map — only these closures change per backend.
190
262
  * @public
191
263
  */
192
264
  export declare interface GuardedTransitionIO {
193
- /** Read the record's current workflow state (the value of its `status` field), or undefined if unknown. */
194
- readState: () => Promise<string | undefined>;
265
+ /**
266
+ * Read the record's current workflow state — the value of its `status` field.
267
+ *
268
+ * Three answers, and the difference between the last two matters:
269
+ * - a string — the record's current state
270
+ * - `undefined` — the record exists but carries no workflow state
271
+ * - `null` — **there is no such record**
272
+ *
273
+ * Collapsing those two into `undefined` is what let an action against a missing record report
274
+ * success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and
275
+ * the write then found nothing to write. Backends must return `null` when the lookup misses.
276
+ */
277
+ readState: () => Promise<string | null | undefined>;
195
278
  /** Persist the record's new workflow state, written verbatim. */
196
279
  writeState: (nextState: string) => Promise<void>;
197
280
  /**
198
- * Persist record field data for a mutate-in-place self-transition, returning the full updated
199
- * record (so the client writeback reflects the new data). Optional: a backend with no data-write
200
- * path (e.g. PostGraphile today, which writes only `status`) omits it, and a self-transition is
201
- * then rejected loudly rather than silently dropped.
281
+ * Persist a record's field data for a self-transition, returning the full record as it now
282
+ * stands (so the client writeback reflects it).
283
+ *
284
+ * **This is an upsert, and it is the create path.** Saving a record is one request whether or
285
+ * not the row is there yet, so there is no create action and no create mutation — `exists` says
286
+ * which case you are in, and the second argument exists only because the dispatcher already
287
+ * knows: it read the record's state to run the guard. When `exists` is false, mint or derive the
288
+ * identity here and return the created record; identity is the backend's business, not the
289
+ * dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that
290
+ * value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.
291
+ *
292
+ * Never return an empty object for a creation: the dispatcher treats that as a backend that
293
+ * only knows how to patch, and fails loudly rather than reporting a save that stored nothing.
294
+ *
295
+ * Optional. A backend with no data-write path omits it, which is how it declines both saving
296
+ * and creating; a self-transition is then rejected loudly rather than silently dropped — unless
297
+ * `runEffect` is supplied, in which case the handler is the persistence path.
202
298
  */
203
- writeData?: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
299
+ writeData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>;
300
+ /**
301
+ * Run the adapter's side effect for this action, after the guard has passed and before any
302
+ * state is written. This is the seam a **database author** wires — see
303
+ * `StonecropPluginOptions.actionHandlers` for the Postgres adapter's registration surface.
304
+ *
305
+ * It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at
306
+ * all: without one, such an action has nothing to apply and fails loudly.
307
+ *
308
+ * Throwing rejects the action, so the dispatcher writes neither data nor state. It does **not**
309
+ * undo writes the handler already made: this guard is storage-agnostic and owns no transaction,
310
+ * and the Postgres adapter in particular dispatches outside one. A handler whose own statements
311
+ * must be all-or-nothing has to wrap them itself.
312
+ *
313
+ * Returning a full record makes it the client writeback payload; returning `undefined` leaves
314
+ * the doctype's own outcome to decide what comes back.
315
+ *
316
+ * @param currentState - The state the guard read, or `undefined` when nothing required reading it
317
+ * @returns The updated record, or `undefined` to leave the result payload to the state outcome
318
+ */
319
+ runEffect?: (currentState: string | undefined) => Promise<unknown>;
204
320
  }
205
321
 
206
322
  /**
@@ -263,6 +379,59 @@ export declare interface StonecropPluginOptions {
263
379
  * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
264
380
  */
265
381
  tables?: Record<string, string>;
382
+ /**
383
+ * Server-side effects for workflow actions, keyed `[doctype name][action key]`.
384
+ *
385
+ * This is the seam that makes a stateless Command executable. `applyGuardedTransition` can
386
+ * apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —
387
+ * but an action that is neither has nothing to apply and fails loudly. Registering a handler
388
+ * here supplies the missing half.
389
+ *
390
+ * **The doctype never names a handler, and a handler never overrides the guard.** The two are
391
+ * authored by different people: a doctype is runtime data edited in DocBuilder by whoever
392
+ * models the workflow, while these run behind the GraphQL surface and belong to whoever owns
393
+ * the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state
394
+ * results), and this keeps the effect (what actually happens). Routing between them is
395
+ * resolved here, on the server, and is never published to the client.
396
+ *
397
+ * Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An
398
+ * unregistered action is not an error in itself: a transition needs no handler. It fails only
399
+ * when the doctype gave the action no outcome either, and the error then names the action and
400
+ * both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * createStonecropPlugin({
405
+ * actionHandlers: {
406
+ * Order: {
407
+ * async recalculateTotal({ pgClient, recordId }) {
408
+ * const { rows } = await pgClient.query({
409
+ * text: 'UPDATE "order" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',
410
+ * values: [recordId],
411
+ * })
412
+ * return rows[0]
413
+ * },
414
+ * },
415
+ * },
416
+ * })
417
+ * ```
418
+ */
419
+ actionHandlers?: Record<string, Record<string, ActionHandler>>;
420
+ /**
421
+ * Row cap applied to `stonecropRecords` when the caller requests no `limit`. Defaults to 200.
422
+ *
423
+ * A row cap is a statement about what this database can afford to serve, so it belongs to
424
+ * whoever owns the database — not to a doctype (which describes the API surface, not the
425
+ * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
426
+ * free to ask for less; they cannot ask for an unbounded scan by omission.
427
+ *
428
+ * `hasMore` reports whether the cap truncated the result, so a capped page is always
429
+ * distinguishable from a complete one without asking for a count.
430
+ *
431
+ * Set to `null` for no default cap. That is the pre-0.17 behaviour and it means an unqualified
432
+ * list query returns the whole table.
433
+ */
434
+ defaultRecordLimit?: number | null;
266
435
  }
267
436
 
268
437
  /**
@@ -291,13 +460,6 @@ export declare const StonecropPreset: GraphileConfig.Preset;
291
460
  */
292
461
  export declare const typeDefs: DocumentNode;
293
462
 
294
- /**
295
- * Validate cross-doctype references (Link fields, inherits, etc.)
296
- * Call after all doctypes are loaded.
297
- * @public
298
- */
299
- export declare function validateReferences(): ValidationError[];
300
-
301
463
  export { ValidationError }
302
464
 
303
465
  export { }