@stonecrop/graphql-middleware 0.30.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,93 +0,0 @@
1
- import { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema';
2
- import { getMeta } from './registry/doctypes';
3
- import { resolveTableName } from './tables';
4
- /**
5
- * Normalize a scalar SQL cell value to a non-empty string, or nothing.
6
- *
7
- * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key
8
- * in the result, and the display text stamped into the payload. Rejecting objects is what each
9
- * of those wants: an object FK is a link that was already expanded, and an object display column
10
- * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it
11
- * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.
12
- */
13
- function scalarText(value) {
14
- if (value == null || typeof value === 'object')
15
- return undefined;
16
- if (typeof value === 'string')
17
- return value === '' ? undefined : value;
18
- if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
19
- return String(value);
20
- }
21
- return undefined;
22
- }
23
- function collectLinkDisplaySpecs(meta, tables) {
24
- const specs = [];
25
- for (const field of flattenFields(meta.fields)) {
26
- if (field.kind !== 'field' || !field.doctype)
27
- continue;
28
- const targetMeta = getMeta(field.doctype);
29
- if (!targetMeta)
30
- continue;
31
- // `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`
32
- // makes at the load gate, so a nomination that parsed is one this can build a SELECT from.
33
- // A hand-rolled scan here admitted `computed` fields, whose column does not exist.
34
- const displayField = getDisplayField(targetMeta.fields, targetMeta.displayField);
35
- if (!displayField)
36
- continue;
37
- specs.push({
38
- fieldname: field.fieldname,
39
- displayField: displayField.fieldname,
40
- targetPkFieldname: getRecordIdField(targetMeta.fields),
41
- targetTable: resolveTableName(targetMeta.name, tables),
42
- });
43
- }
44
- return specs;
45
- }
46
- /**
47
- * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a
48
- * `displayField`. Expanded relations (object values) are skipped.
49
- *
50
- * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch
51
- * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
52
- * loader exists to prevent, and does so invisibly, since the result is identical either way.
53
- */
54
- export async function enrichLinkDisplayFields(pgClient, meta, rows, tables, debugSql) {
55
- const specs = collectLinkDisplaySpecs(meta, tables);
56
- if (specs.length === 0 || rows.length === 0)
57
- return;
58
- await Promise.all(specs.map(async (spec) => {
59
- const ids = new Set();
60
- for (const row of rows) {
61
- const id = scalarText(row[spec.fieldname]);
62
- if (id !== undefined)
63
- ids.add(id);
64
- }
65
- if (ids.size === 0)
66
- return;
67
- const pkColumn = camelToSnake(spec.targetPkFieldname);
68
- const displayColumn = camelToSnake(spec.displayField);
69
- const displayAlias = displayColumn !== spec.displayField ? `"${displayColumn}" AS "${spec.displayField}"` : `"${spec.displayField}"`;
70
- const { rows: displayRows } = await debugSql(pgClient, {
71
- text: `SELECT "${pkColumn}" AS "${spec.targetPkFieldname}", ${displayAlias} FROM ${spec.targetTable} WHERE "${pkColumn}"::text = ANY($1::text[])`,
72
- values: [Array.from(ids)],
73
- });
74
- const displayById = new Map();
75
- for (const displayRow of displayRows) {
76
- const key = scalarText(displayRow[spec.targetPkFieldname]);
77
- const text = scalarText(displayRow[spec.displayField]);
78
- if (key === undefined || text === undefined)
79
- continue;
80
- displayById.set(key, text);
81
- }
82
- for (const row of rows) {
83
- const rawId = row[spec.fieldname];
84
- const idKey = scalarText(rawId);
85
- if (idKey === undefined)
86
- continue;
87
- const displayText = displayById.get(idKey);
88
- if (displayText === undefined)
89
- continue;
90
- row[spec.fieldname] = { id: rawId, displayText };
91
- }
92
- }));
93
- }
@@ -1,174 +0,0 @@
1
- import type { DoctypeMeta } from '@stonecrop/schema';
2
- import type { PgClient } from '@dataplan/pg';
3
- import { GraphileConfig } from 'postgraphile/graphile-build';
4
- /**
5
- * Everything a server-side action handler is given when `stonecropAction` dispatches to it.
6
- *
7
- * A context object rather than positional parameters so the set can grow without breaking
8
- * registered handlers — the adapters that supply these live in consumer repositories.
9
- * @public
10
- */
11
- export interface ActionHandlerContext {
12
- /**
13
- * Active database client for the current request. **It is inside the action's transaction.**
14
- *
15
- * The guard read, this handler, and the state write all run on this client inside one
16
- * transaction, so the action is atomic: throw, and everything this handler wrote is rolled
17
- * back along with the state change. Returning normally commits the lot.
18
- *
19
- * Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would
20
- * close the action's transaction early, committing work the guard may still reject. If you
21
- * need to undo part of your own work without failing the action, use a `SAVEPOINT`.
22
- *
23
- * Work sent to a *different* connection is outside all of this and will not be rolled back —
24
- * so use this client rather than opening one of your own.
25
- *
26
- * Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's
27
- * own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that
28
- * returns raw rows therefore leaks snake_case keys to the client. Alias in SQL
29
- * (`"display_name" AS "displayName"`) or convert with `snakeToCamel` from `@stonecrop/schema`.
30
- */
31
- pgClient: PgClient;
32
- /** The doctype the action was dispatched against, as the client sent it. */
33
- doctype: string;
34
- /** The action's key in `workflow.actions` — the same string the handler was registered under. */
35
- action: string;
36
- /** The resolved doctype metadata, for field names, the primary key, and the workflow. */
37
- meta: DoctypeMeta;
38
- /** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */
39
- recordId?: string | number;
40
- /**
41
- * The record field data the client sent (`args[0].data`).
42
- *
43
- * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has
44
- * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist
45
- * the fields the action is allowed to touch.
46
- */
47
- data: Record<string, unknown>;
48
- /** The full argument envelope, for the actions that need more than the first record. */
49
- args: unknown[];
50
- /** The state the guard read, or `undefined` when nothing about the action required reading it. */
51
- currentState?: string;
52
- }
53
- /**
54
- * A server-side effect for one doctype action, supplied by whoever owns the database.
55
- *
56
- * Throwing rejects the action and no state is written. Returning the updated record makes it the
57
- * client writeback payload; returning `undefined` leaves the doctype's own outcome to decide.
58
- *
59
- * The return value is passed through verbatim as `StonecropActionResult.data`, so it must be
60
- * API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and
61
- * ADR 0007.
62
- * @public
63
- */
64
- export type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>;
65
- /**
66
- * Options for creating a Stonecrop PostGraphile plugin.
67
- * @public
68
- */
69
- export interface StonecropPluginOptions {
70
- /**
71
- * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks
72
- * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.
73
- */
74
- debug?: boolean;
75
- /**
76
- * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.
77
- * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).
78
- * SQL fragments and subqueries are not supported.
79
- * When absent for a doctype, the table name is derived as `pascalToSnake(doctype.name)`, so
80
- * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a
81
- * PascalCase name: `camelToSnake('User')` is `_user`.)
82
- */
83
- tables?: Record<string, string>;
84
- /**
85
- * Server-side effects for workflow actions, keyed `[doctype name][action key]`.
86
- *
87
- * This is the seam that makes a stateless Command executable. `applyGuardedTransition` can
88
- * apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —
89
- * but an action that is neither has nothing to apply and fails loudly. Registering a handler
90
- * here supplies the missing half.
91
- *
92
- * **The doctype never names a handler, and a handler never overrides the guard.** The two are
93
- * authored by different people: a doctype is runtime data edited in DocBuilder by whoever
94
- * models the workflow, while these run behind the GraphQL surface and belong to whoever owns
95
- * the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state
96
- * results), and this keeps the effect (what actually happens). Routing between them is
97
- * resolved here, on the server, and is never published to the client.
98
- *
99
- * Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An
100
- * unregistered action is not an error in itself: a transition needs no handler. It fails only
101
- * when the doctype gave the action no outcome either, and the error then names the action and
102
- * both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.
103
- *
104
- * @example
105
- * ```ts
106
- * createStonecropPlugin({
107
- * actionHandlers: {
108
- * Order: {
109
- * async recalculateTotal({ pgClient, recordId }) {
110
- * const { rows } = await pgClient.query({
111
- * text: 'UPDATE "order" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',
112
- * values: [recordId],
113
- * })
114
- * return rows[0]
115
- * },
116
- * },
117
- * },
118
- * })
119
- * ```
120
- */
121
- actionHandlers?: Record<string, Record<string, ActionHandler>>;
122
- /**
123
- * Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests
124
- * no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults
125
- * to 200.
126
- *
127
- * A row cap is a statement about what this database can afford to serve, so it belongs to
128
- * whoever owns the database — not to a doctype (which describes the API surface, not the
129
- * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay
130
- * free to ask for less; they cannot ask for an unbounded scan by omission.
131
- *
132
- * One number covers both reads because a link *is* a list, fetched a different way. It used to
133
- * be capped at a hard-coded 50 that no option could reach, which is how an operator watching a
134
- * slow query found there was no knob to turn.
135
- *
136
- * Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a
137
- * partial answer is distinguishable from a complete one without asking for a count. That
138
- * matters more for a link than for a list: a link cannot be paged, so a client that writes
139
- * back a truncated relation deletes the rows it was never sent.
140
- *
141
- * Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an
142
- * unqualified list query returns the whole table and a link returns the whole relation.
143
- */
144
- defaultRecordLimit?: number | null;
145
- }
146
- /**
147
- * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
148
- *
149
- * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
150
- * during schema construction — it does not need to be supplied by the caller.
151
- *
152
- * @param options - Optional plugin configuration
153
- * @returns A PostGraphile plugin
154
- * @public
155
- */
156
- export declare const createStonecropPlugin: (options?: StonecropPluginOptions) => GraphileConfig.Plugin;
157
- /**
158
- * Derive a quoted SQL column list from doctype field definitions.
159
- * Applies camelToSnake to each fieldname to get the DB column name, then
160
- * aliases it back to the fieldname so result rows carry API-layer keys.
161
- * Excludes `computed` fields (no backing DB column), Fieldset
162
- * containers (recursing into their children instead), and *expanding* links
163
- * (relations fetched separately). An inline link keeps its FK column here.
164
- *
165
- * Exported for unit testing (not re-exported from the package index).
166
- */
167
- export declare function getSqlColumns(meta: DoctypeMeta): string;
168
- /**
169
- * Resolve the PostgreSQL FROM clause target for a doctype.
170
- * Uses the `tables` override map first; falls back to camelToSnake(name).
171
- * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
172
- * Values must be bare identifiers or schema.table pairs — not SQL fragments.
173
- */
174
- //# sourceMappingURL=postgraphile.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,WAAW,EAAiD,MAAM,mBAAmB,CAAA;AAGjH,OAAO,KAAK,EAAE,QAAQ,EAAc,MAAM,cAAc,CAAA;AAExD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAW5D;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACpC;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,EAAE,QAAQ,CAAA;IAClB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAA;IACf,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAA;IACd,yFAAyF;IACzF,IAAI,EAAE,WAAW,CAAA;IACjB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IAC1B;;;;;;OAMG;IACH,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,wFAAwF;IACxF,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,kGAAkG;IAClG,YAAY,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;AAE/E;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IAC9D;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAClC;AAmCD;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MAmuB3F,CAAA;AA0BD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAQvD;AAkID;;;;;GAKG"}