@stonecrop/graphql-middleware 0.46.1 → 0.48.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/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/fields.ts","../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/tables.ts","../src/columns.ts","../src/link-display.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import type { DoctypeField, ValueField } from '@stonecrop/schema'\nimport { flattenFields } from '@stonecrop/schema'\n\n// Re-exported so this module stays the one place the adapter asks about a doctype's fields, while\n// the definition itself lives in `@stonecrop/schema`. It moved there because `DoctypeMeta`'s own\n// validation needs the same descent, and the copy it had written instead scanned top level only —\n// so the load gate and the read path disagreed about what a doctype declares, which is exactly\n// what keeping one definition is for.\nexport { flattenFields }\n\n/**\n * The fields that have a database column of their own — the one definition of that question.\n *\n * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is\n * declared precisely to state it has no column, and a container (a table field) is a relation\n * rather than a value. Everything else names a column.\n *\n * This is deliberately **not** the same question as \"does this column belong in a record payload\".\n * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`\n * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the\n * two is how the read path came to drop the very column its expansion needed. Callers wanting the\n * payload projection filter this further by render mode; callers asking whether a column exists —\n * link validation, and the write path deciding what it may set — want it unfiltered.\n *\n * Extracted because the rule had grown three statements across two modules, one of them a comment\n * reading \"mirrors `collectColumns`\". A rule that has to be mirrored by hand is one edit away from\n * the read path and the validator disagreeing about what a doctype declares.\n */\nexport function columnBackedFields(fields: readonly DoctypeField[]): ValueField[] {\n\treturn flattenFields(fields).filter((f): f is ValueField => f.kind === 'field' && !f.computed)\n}\n","import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nimport { columnBackedFields, flattenFields } from '../fields'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(typeof data === 'object' && data !== null ? data : {}), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\tconst direct = doctypeRegistry.get(name)\n\tif (direct) return direct\n\t// Fallback: find by slug (links reference doctypes by slug, not name)\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\tif (doctype.slug === name) return doctype\n\t}\n\treturn undefined\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate doctype references — link targets, `inherits`, and each link's binding — against what\n * is loaded.\n *\n * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by\n * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as\n * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for\n * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.\n * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same\n * question the runtime asks.\n *\n * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers\n * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the\n * permissive direction.\n *\n * The **binding** checks are the same defect class as an unresolvable target, one step further in:\n * a link whose target resolves can still name no way to reach the rows, and the reader's answer for\n * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely\n * empty. Both halves of a declaration are `.optional()` in the schema because which one is required\n * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.\n *\n * Only what the runtime actually consults is required. A `backlink` naming a column the target\n * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;\n * the check exists for the silent cases, not to restate the database's own errors.\n *\n * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that\n * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only\n * meaningful after this module's own loaders have run.\n *\n * @internal\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && getMeta(doctype.inherits) === undefined) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\tconst fields = flattenFields(doctype.fields)\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && getMeta(target) === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'doctype'],\n\t\t\t\t\tmessage: `Link references unknown doctype: ${target}`,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Check link-declaration targets (component-primary links live in the `links` map)\n\t\tif (doctype.links) {\n\t\t\tconst declared = new Set(fields.map(f => f.fieldname))\n\t\t\t// A foreign key is read from a column, so a link can only bind to a field that has one.\n\t\t\t// The rule itself lives in one place — see `columnBackedFields` — because the read path,\n\t\t\t// the write path and this check all have to answer it the same way.\n\t\t\tconst columnBacked = new Set(columnBackedFields(doctype.fields).map(f => f.fieldname))\n\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (getMeta(link.target) === undefined) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'target'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${link.target}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// A custom fetch strategy hands the whole read to its handler, which is given the\n\t\t\t\t// row and the declaration and finds the target however it likes. The runtime returns\n\t\t\t\t// before consulting either binding below, so requiring one would refuse a link that\n\t\t\t\t// works.\n\t\t\t\tif (link.fetch?.method === 'custom') continue\n\n\t\t\t\t// The two cardinalities bind through different halves of the declaration, so the\n\t\t\t\t// check has to split the same way the reader does.\n\t\t\t\tif (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') {\n\t\t\t\t\t// Many-side: the target rows are found by a column on the *target* table, so\n\t\t\t\t\t// this doctype needs no field of its own — and the in-repo hosts disagree on\n\t\t\t\t\t// whether one exists, which is why only `backlink` can be required here.\n\t\t\t\t\tif (!link.backlink) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'backlink'],\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t`Link \"${key}\" is ${link.cardinality} but names no \\`backlink\\`, so the runtime cannot ` +\n\t\t\t\t\t\t\t\t`find the target rows and drops the link with no error. Name the field on \"${link.target}\" ` +\n\t\t\t\t\t\t\t\t`that points back to this doctype.`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// One-side: the foreign key is a column on *this* table, read as\n\t\t\t\t// `link.fieldname ?? key`. A name matching no declared field is not selected, so the\n\t\t\t\t// link resolves to null forever and reads as \"this record has no such relation\".\n\t\t\t\tconst fieldname = link.fieldname ?? key\n\t\t\t\tif (!columnBacked.has(fieldname)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\t// Point at whichever half actually carries the binding: the `fieldname`\n\t\t\t\t\t\t// property when it is set, otherwise the key itself. Naming `target` here\n\t\t\t\t\t\t// would send the reader to the one part that resolved correctly.\n\t\t\t\t\t\tpath: link.fieldname ? [doctype.name, 'links', key, 'fieldname'] : [doctype.name, 'links', key],\n\t\t\t\t\t\t// Two different repairs, so two different diagnoses: a name nothing declares\n\t\t\t\t\t\t// is a typo, while a name that resolves to a column-less field is a binding\n\t\t\t\t\t\t// pointed at the wrong one of several real fields.\n\t\t\t\t\t\tmessage: declared.has(fieldname)\n\t\t\t\t\t\t\t? `Link \"${key}\" binds to field \"${fieldname}\", which has no database column of its own — ` +\n\t\t\t\t\t\t\t\t`it is computed, or a container rather than a value — so there is no foreign key to read ` +\n\t\t\t\t\t\t\t\t`and the record read fails on the missing column. Bind the link to the field holding the ` +\n\t\t\t\t\t\t\t\t`foreign key.`\n\t\t\t\t\t\t\t: `Link \"${key}\" binds to field \"${fieldname}\", which this doctype does not declare, so it ` +\n\t\t\t\t\t\t\t\t`resolves to null with no error. Declare that field, or set \\`fieldname\\` to the field ` +\n\t\t\t\t\t\t\t\t`holding the foreign key. (A link's key is its fieldname unless \\`fieldname\\` overrides it.)`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { PgClient } from '@dataplan/pg'\nimport type { LinkDeclaration } from '@stonecrop/schema'\n\n/**\n * Handler for a custom fetch strategy on a link declaration.\n * Called during `stonecropRecord` resolution when `link.fetch.method === 'custom'`.\n *\n * @param pgClient - Active database client for the current request\n * @param parentRecord - Resolved parent record (scalar fields already populated)\n * @param link - The link declaration, giving access to cardinality and other metadata\n * @returns A single linked record or an array depending on `link.cardinality`\n * @public\n */\nexport type FetchHandler = (\n\tpgClient: PgClient,\n\tparentRecord: Record<string, unknown>,\n\tlink: LinkDeclaration\n) => Promise<Record<string, unknown> | Record<string, unknown>[]>\n\nconst registry = new Map<string, FetchHandler>()\n\n/**\n * Register a custom fetch handler by name.\n * The name must match the `handler` field on a `CustomFetch` strategy declaration.\n * @public\n */\nexport function registerFetchHandler(name: string, handler: FetchHandler): void {\n\tregistry.set(name, handler)\n}\n\n/**\n * Retrieve a registered fetch handler by name.\n * Returns `undefined` if no handler has been registered under that name.\n * @public\n */\nexport function getFetchHandler(name: string): FetchHandler | undefined {\n\treturn registry.get(name)\n}\n\n/**\n * Remove all registered fetch handlers. Primarily for test isolation.\n * @public\n */\nexport function clearFetchHandlers(): void {\n\tregistry.clear()\n}\n","import { isActionAllowedInState } from '@stonecrop/schema'\n\n/**\n * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.\n * The same guard runs whether the record lives in Postgres, a mock executor, or an\n * in-memory Map — only these closures change per backend.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/**\n\t * Read the record's current workflow state — the value of its `status` field.\n\t *\n\t * Three answers, and the difference between the last two matters: a string is the record's\n\t * current state, `undefined` means the record exists but carries no workflow state, and `null`\n\t * means **there is no such record**.\n\t *\n\t * Collapsing those two into `undefined` is what let an action against a missing record report\n\t * success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and\n\t * the write then found nothing to write. Backends must return `null` when the lookup misses.\n\t */\n\treadState: () => Promise<string | null | undefined>\n\t/** Persist the record's new workflow state, written verbatim. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Persist a record's field data for a self-transition, returning the full record as it now\n\t * stands, which states its identity (the only place a created record's key is known).\n\t *\n\t * **This is an upsert, and it is the create path.** Saving a record is one request whether or\n\t * not the row is there yet, so there is no create action and no create mutation — `exists` says\n\t * which case you are in, and the second argument exists only because the dispatcher already\n\t * knows: it read the record's state to run the guard. When `exists` is false, mint or derive the\n\t * identity here and return the created record; identity is the backend's business, not the\n\t * dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that\n\t * value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.\n\t *\n\t * Never return an empty object for a creation: the dispatcher treats that as a backend that\n\t * only knows how to patch, and fails loudly rather than reporting a save that stored nothing.\n\t *\n\t * Optional. A backend with no data-write path omits it, which is how it declines both saving\n\t * and creating; a self-transition is then rejected loudly rather than silently dropped — unless\n\t * `runEffect` is supplied, in which case the handler is the persistence path.\n\t */\n\twriteData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>\n\t/**\n\t * Run the adapter's side effect for this action, after the guard has passed and before any\n\t * state is written. This is the seam a **database author** wires — see\n\t * `StonecropPluginOptions.actionHandlers` for the Postgres adapter's registration surface.\n\t *\n\t * It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at\n\t * all: without one, such an action has nothing to apply and fails loudly.\n\t *\n\t * Throwing rejects the action, so the dispatcher writes neither data nor state. It does **not**\n\t * undo writes the handler already made: this guard is storage-agnostic and owns no transaction,\n\t * and the Postgres adapter in particular dispatches outside one. A handler whose own statements\n\t * must be all-or-nothing has to wrap them itself.\n\t *\n\t * What it returns becomes the result's `data`, verbatim; returning `undefined` leaves the\n\t * doctype's own outcome to decide `data`. The client stores the adapter's read of the record,\n\t * never this.\n\t *\n\t * @param currentState - The state the guard read, or `undefined` when nothing required reading it\n\t * @returns The updated record, or `undefined` to leave the result payload to the state outcome\n\t */\n\trunEffect?: (currentState: string | undefined) => Promise<unknown>\n}\n\n/**\n * Apply a workflow action on the server, enforcing `allowedStates`.\n *\n * The server owns the transition: it reads the record's authoritative current state,\n * rejects the action when `isActionAllowedInState` denies it, then applies the outcome.\n * Storage access is injected via `io` so this one guard serves every backend and can never\n * disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.\n *\n * **The doctype decides whether an action may run and what state results; the adapter decides\n * what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the\n * doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever\n * owns the database. Neither names the other: an action never carries a handler name, and a\n * handler never overrides the guard.\n *\n * There are four action shapes this distinguishes:\n *\n * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\n *\n * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current\n * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.\n * When the target record does not exist the same write creates it — saving a record is one\n * request whether or not the row is there yet, so there is no separate create action, no create\n * mutation, and no second write path for it.\n *\n * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole\n * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.\n *\n * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine\n * authoring mistake or a command whose handler was never wired. It fails loudly before touching\n * the backend rather than reporting a false success.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`\n * @param io - Backend read/write closures, plus the optional adapter-owned effect\n * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)\n * @returns Action result envelope — the freshest record the backend produced, or the resulting state\n * @public\n */\nexport async function applyGuardedTransition(\n\tactionDef: { label?: string; allowedStates?: string[]; nextState?: string; selfTransition?: boolean },\n\tio: GuardedTransitionIO,\n\tdata?: Record<string, unknown>\n): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\tconst label = actionDef.label ?? 'unknown'\n\tconst isSelfTransition = actionDef.selfTransition === true\n\tconst hasStateOutcome = isSelfTransition || actionDef.nextState != null\n\n\t// Nothing to apply and no effect registered — fail loudly WITHOUT touching the backend.\n\t// This is the honest report for both causes: an action authored with no outcome, and a\n\t// command whose server handler the adapter never registered.\n\tif (!hasStateOutcome && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`,\n\t\t}\n\t}\n\n\t// A self-transition exists to persist data; with no way at all to do that — no data write, no\n\t// create, no effect — reject before running anything rather than half-applying.\n\tif (isSelfTransition && !io.writeData && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" persists record data in place, which this backend does not support.`,\n\t\t}\n\t}\n\n\t// Read the authoritative state only when something actually consumes it: the guard, or a\n\t// state outcome that the caller's readState is paired with. A handler-only command on a\n\t// doctype with no `status` column must not be forced through a read it never uses.\n\tconst isGuarded = (actionDef.allowedStates?.length ?? 0) > 0\n\tlet currentState: string | undefined\n\tif (isGuarded || hasStateOutcome) {\n\t\tconst state = await io.readState()\n\t\t// A missing record is reported, never guarded around. Reaching the guard with a state of\n\t\t// `''` produced two wrong answers depending only on whether the action declared\n\t\t// `allowedStates`: a misleading \"not allowed from state: (unknown)\" when it did, and a\n\t\t// silent `{ success: true }` writing nothing when it did not.\n\t\tif (state === null) {\n\t\t\t// A self-transition against a record that is not there is a create — the same write,\n\t\t\t// against a row that does not exist yet. The guard is deliberately skipped:\n\t\t\t// `allowedStates` constrains movement between states, and a record being created is not\n\t\t\t// in one; its initial state is the backend's to set.\n\t\t\t//\n\t\t\t// A registered effect does NOT run here. An effect is written against an existing row,\n\t\t\t// and firing it against a just-created one is a different contract than the one it was\n\t\t\t// registered under; making creation observable to effects is deferred rather than\n\t\t\t// guessed at.\n\t\t\tif (isSelfTransition && io.writeData) {\n\t\t\t\tconst created = await io.writeData(data ?? {}, false)\n\t\t\t\t// A backend that only knows how to patch returns nothing here, having matched no\n\t\t\t\t// row. Reporting that as success is the exact bug the `null` answer above exists to\n\t\t\t\t// kill, so it must not come back through the create path.\n\t\t\t\tif (!created || Object.keys(created).length === 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: `Action \"${label}\" targets a record that does not exist, and the backend did not create it.`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { success: true, data: created, error: null }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" targets a record that does not exist — nothing was executed.`,\n\t\t\t}\n\t\t}\n\t\tcurrentState = state ?? ''\n\t}\n\n\tif (!isActionAllowedInState(actionDef, currentState ?? '')) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action not allowed from state: ${currentState || '(unknown)'}`,\n\t\t}\n\t}\n\n\t// The effect runs after the guard and before any write, so a handler that rejects cannot\n\t// leave the record in the target state. Its throw is attributed to the action by name —\n\t// the adapter's handler is code the doctype author cannot see, so an anonymous failure\n\t// would be undebuggable from either side.\n\tlet effectResult: unknown\n\tif (io.runEffect) {\n\t\ttry {\n\t\t\teffectResult = await io.runEffect(currentState)\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t// Self-transition: mutate record data in place, keep the current state. The full updated\n\t// record is returned so a created record's identity is known. When the backend has no\n\t// data-write path the effect above already did the persisting (guarded at the top).\n\tif (isSelfTransition) {\n\t\tconst record = io.writeData ? await io.writeData(data ?? {}, true) : effectResult\n\t\treturn { success: true, data: record ?? null, error: null }\n\t}\n\n\t// NON-ATOMIC: the current state is read above and nextState written here as two\n\t// separate statements — and a registered effect runs between them. Two concurrent\n\t// transitions on the same record can both pass the guard before either writes, so both\n\t// \"succeed\" even when the workflow intended them to be mutually exclusive. Closing this\n\t// requires guarding and writing in one statement — an atomic\n\t// `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)` — and reporting\n\t// \"no rows updated\" as a rejected transition. Deferred for now.\n\tif (actionDef.nextState == null) {\n\t\t// A stateless command: the effect (guaranteed present by the top guard) is the whole\n\t\t// outcome. It must not move the record — that is the doctype's call, not the handler's.\n\t\treturn { success: true, data: effectResult ?? null, error: null }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\t// The freshest thing the backend produced wins: a handler that returned a record describes\n\t// the row better than the state alone, which is all a bare transition knows.\n\treturn {\n\t\tsuccess: true,\n\t\tdata: effectResult ?? { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { pascalToSnake } from '@stonecrop/schema'\n\n/** A table a doctype reads from, as named before quoting. `schema` is absent for an unqualified name. */\nexport interface TableRef {\n\tschema?: string\n\tname: string\n}\n\n/**\n * The table a doctype reads from: the `tables` override when the adapter supplies one, otherwise the\n * doctype name snake-cased.\n *\n * The one definition of that mapping. It lives in its own module rather than beside either caller\n * because the plugin imports the link-display enrichment, so the enrichment cannot import back —\n * and the copy it made instead was byte-identical, which is the state a mapping is in right before\n * one side learns about schema-qualified names and the other does not.\n *\n * A dotted override is read as `schema.table`, so a table in a non-default Postgres schema keeps\n * its schema instead of becoming one name containing a dot.\n */\nexport function resolveTable(name: string, tables?: Record<string, string>): TableRef {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn { schema: target.slice(0, dotIndex), name: target.slice(dotIndex + 1) }\n\t}\n\treturn { name: target }\n}\n\n/** The quoted SQL table a doctype reads from (see `resolveTable`). */\nexport function resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst table = resolveTable(name, tables)\n\treturn table.schema === undefined ? `\"${table.name}\"` : `\"${table.schema}\".\"${table.name}\"`\n}\n","import { LIST_TYPES, TYPES } from '@dataplan/pg'\nimport type { PgCodec, PgCodecAttribute, PgExecutor } from '@dataplan/pg'\nimport { sql } from 'postgraphile/pg-sql2'\nimport type { SQL } from 'postgraphile/pg-sql2'\nimport { Temporal } from 'temporal-polyfill'\n\nimport { resolveTable, resolveTableName } from './tables'\n\n/** A column to read, and the key its value comes back under. */\nexport interface ColumnSelection {\n\tcolumn: string\n\talias: string\n}\n\n/** One doctype's table, with a select list whose values read as PostGraphile reads them. */\nexport interface ColumnSelect {\n\t/** The quoted table. */\n\ttable: string\n\t/** Each column cast to text the way PostGraphile casts it, under its alias. */\n\tlist: string\n\t/** Decodes every selected value in place with the codec PostGraphile decodes it with. */\n\tdecodeRows(rows: readonly Record<string, unknown>[]): void\n}\n\n/** Builds the select list for a doctype's columns, and the SQL that binds a value to one. */\nexport interface ColumnReader {\n\tselect(doctype: string, selections: readonly ColumnSelection[]): ColumnSelect\n\t/** `placeholder` as the value for `column`, cast where the column needs its value converted. */\n\tbind(doctype: string, column: string, placeholder: string): string\n\t/** Whether a write may set `column`: not one the database fills itself, which PostGraphile marks as neither insertable nor updatable. */\n\twritable(doctype: string, column: string): boolean\n}\n\n/** A domain's underlying type, through any domains stacked on it. */\nconst baseCodec = (codec: PgCodec): PgCodec => (codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec)\n\n/** How a column whose values carry no zone is converted into the moments they name. */\ninterface MomentConversion {\n\t/** The type Postgres converts it to, through the database's zone. */\n\ttype: 'timestamptz' | 'timestamptz[]'\n\tcastSql: SQL\n\t/** Reads the converted value as PostGraphile reads that type. */\n\tcodec: PgCodec\n}\n\n/**\n * The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which\n * names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast\n * Postgres itself makes through the database's zone, so a value leaves as a moment and a moment\n * comes back to the same reading. Every other column needs none.\n *\n * Not PostGraphile's own text for it: that carries no zone, so a browser reads it in its own zone\n * and sends back UTC, and every save moved the stored time by the user's offset.\n */\nconst momentConversion = (codec: PgCodec): MomentConversion | undefined => {\n\tif (baseCodec(codec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz', castSql: sql`::timestamptz`, codec: TYPES.timestamptz }\n\t}\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz[]', castSql: sql`::timestamptz[]`, codec: LIST_TYPES.timestamptz }\n\t}\n\treturn undefined\n}\n\nconst INTERVAL_PARTS = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] as const\n\n/**\n * An interval, as PostGraphile decodes it, written as an ISO 8601 duration (`P1DT2H30M`): the value\n * a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Not PostGraphile's object,\n * which every other backend would have to imitate. Postgres writes an ISO 8601 duration back natively.\n *\n * Postgres signs each part apart, so it can hold \"a day less an hour\", which no ISO 8601 duration can.\n * Such an interval throws rather than being read as some other length.\n */\nconst isoDuration = (interval: unknown, describe: () => string): string => {\n\tconst part = (name: (typeof INTERVAL_PARTS)[number]) => {\n\t\tconst value: unknown = interval instanceof Object ? Reflect.get(interval, name) : undefined\n\t\treturn typeof value === 'number' ? value : 0\n\t}\n\tconst parts = INTERVAL_PARTS.map(part)\n\tif (parts.some(value => value > 0) && parts.some(value => value < 0)) {\n\t\tthrow new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`)\n\t}\n\tconst microseconds = Math.round(part('seconds') * 1e6)\n\treturn Temporal.Duration.from({\n\t\tyears: part('years'),\n\t\tmonths: part('months'),\n\t\tdays: part('days'),\n\t\thours: part('hours'),\n\t\tminutes: part('minutes'),\n\t\tseconds: Math.trunc(microseconds / 1e6),\n\t\tmilliseconds: Math.trunc((microseconds % 1e6) / 1e3),\n\t\tmicroseconds: microseconds % 1e3,\n\t}).toString()\n}\n\nconst readIntervalList = (intervals: unknown, describe: () => string): unknown =>\n\tArray.isArray(intervals)\n\t\t? intervals.map((interval: unknown) => (interval === null ? null : isoDuration(interval, describe)))\n\t\t: intervals\n\n/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */\nconst intervalShape = (codec: PgCodec): 'one' | 'list' | undefined => {\n\tif (baseCodec(codec) === TYPES.interval) return 'one'\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.interval) return 'list'\n\treturn undefined\n}\n\n/**\n * Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each\n * value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is\n * `2026-01-01`. Two exceptions: a `timestamp`, or a list of them, served as the moment each names in\n * the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`), and an\n * `interval`, or a list of them, served as an ISO 8601 duration (see `isoDuration`).\n *\n * Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,\n * which names another day or hour outside UTC, and a save writes that shifted value back. Not a\n * process-wide `setTypeParser` either, which changes every other `pg` query in the host.\n */\nexport function createColumnReader(\n\tcodecs: Readonly<Record<string, PgCodec>>,\n\texecutor: PgExecutor,\n\ttables?: Record<string, string>\n): ColumnReader {\n\tconst tableCodecsByName = new Map<string, PgCodec[]>()\n\tfor (const codec of Object.values(codecs)) {\n\t\tconst pg = codec.extensions?.pg\n\t\tif (!codec.attributes || !codec.extensions?.isTableLike || !pg || codec.executor !== executor) continue\n\t\ttableCodecsByName.set(pg.name, [...(tableCodecsByName.get(pg.name) ?? []), codec])\n\t}\n\n\tconst findTableCodec = (doctype: string): PgCodec => {\n\t\tconst table = resolveTable(doctype, tables)\n\t\tconst matches = (tableCodecsByName.get(table.name) ?? []).filter(\n\t\t\tcodec => table.schema === undefined || codec.extensions?.pg?.schemaName === table.schema\n\t\t)\n\t\tif (matches.length === 1) return matches[0]\n\t\tconst quoted = resolveTableName(doctype, tables)\n\t\tif (matches.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" reads ${quoted}, which PostGraphile has not introspected, so its columns ` +\n\t\t\t\t\t`cannot be read the way PostGraphile reads them. Add the table's schema to the pgService, ` +\n\t\t\t\t\t`or map the doctype in \\`tables\\` to a table PostGraphile knows.`\n\t\t\t)\n\t\t}\n\t\tconst schemas = matches.map(codec => codec.extensions?.pg?.schemaName).join(', ')\n\t\tthrow new Error(\n\t\t\t`Doctype \"${doctype}\" reads ${quoted}, a name PostGraphile knows in more than one schema ` +\n\t\t\t\t`(${schemas}). Map the doctype in \\`tables\\` to \"schema.table\".`\n\t\t)\n\t}\n\n\tconst findAttribute = (doctype: string, tableCodec: PgCodec, column: string): PgCodecAttribute => {\n\t\tconst attribute = tableCodec.attributes?.[column]\n\t\tif (!attribute) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" declares a field for column \"${column}\", which ${resolveTableName(doctype, tables)} does not have.`\n\t\t\t)\n\t\t}\n\t\treturn attribute\n\t}\n\n\treturn {\n\t\tselect(doctype, selections) {\n\t\t\tconst tableCodec = findTableCodec(doctype)\n\t\t\tconst table = resolveTableName(doctype, tables)\n\t\t\t// Keyed by alias, so a column selected twice under one key is decoded once, as `pg` keeps one.\n\t\t\tconst decoders = new Map<string, (value: string) => unknown>()\n\t\t\tconst list = selections\n\t\t\t\t.map(({ column, alias }) => {\n\t\t\t\t\tconst columnCodec = findAttribute(doctype, tableCodec, column).codec\n\t\t\t\t\tconst conversion = momentConversion(columnCodec)\n\t\t\t\t\tconst readCodec = conversion?.codec ?? columnCodec\n\t\t\t\t\tconst columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column)\n\t\t\t\t\tconst cast = readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`\n\t\t\t\t\tconst compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`)\n\t\t\t\t\t// This list is spliced into SQL whose placeholders the caller numbers, so a cast carrying\n\t\t\t\t\t// its own `$1` would silently bind the caller's first value.\n\t\t\t\t\tif (compiled.values.length > 0) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The codec for ${table}.\"${column}\" casts with a bound value, which this adapter cannot select.`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst shape = intervalShape(columnCodec)\n\t\t\t\t\tconst describe = (text: string) => () => `\"${alias}\" from ${table} (${text})`\n\t\t\t\t\tdecoders.set(\n\t\t\t\t\t\talias,\n\t\t\t\t\t\tshape === 'one'\n\t\t\t\t\t\t\t? text => isoDuration(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t: shape === 'list'\n\t\t\t\t\t\t\t\t? text => readIntervalList(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t\t: readCodec.fromPg\n\t\t\t\t\t)\n\t\t\t\t\treturn compiled.text\n\t\t\t\t})\n\t\t\t\t.join(', ')\n\n\t\t\treturn {\n\t\t\t\ttable,\n\t\t\t\tlist,\n\t\t\t\tdecodeRows(rows) {\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tfor (const [alias, fromPg] of decoders) {\n\t\t\t\t\t\t\tconst value = row[alias]\n\t\t\t\t\t\t\tif (value === null) continue\n\t\t\t\t\t\t\t// The list casts every column to text, so anything else is a row this select did not\n\t\t\t\t\t\t\t// produce, or one decoded already.\n\t\t\t\t\t\t\tif (typeof value !== 'string') {\n\t\t\t\t\t\t\t\tthrow new Error(`\"${alias}\" from ${table} is ${typeof value}, not the text its select returns.`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow[alias] = fromPg(value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\n\t\tbind(doctype, column, placeholder) {\n\t\t\tconst conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec)\n\t\t\treturn conversion ? `${placeholder}::${conversion.type}` : placeholder\n\t\t},\n\n\t\twritable(doctype, column) {\n\t\t\tconst { extensions } = findAttribute(doctype, findTableCodec(doctype), column)\n\t\t\treturn extensions?.isInsertable !== false || extensions?.isUpdatable !== false\n\t\t},\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema'\nimport type { PgClient } from '@dataplan/pg'\n\nimport type { ColumnReader } from './columns'\nimport { getMeta } from './registry/doctypes'\n\ntype SqlQueryFn = (\n\tpgClient: PgClient,\n\tquery: { text: string; values?: unknown[] }\n) => Promise<{ rows: readonly Record<string, unknown>[] }>\n\ninterface LinkDisplaySpec {\n\tfieldname: string\n\tdisplayField: string\n\ttargetPkFieldname: string\n\ttargetDoctype: string\n}\n\n/**\n * Normalize a scalar SQL cell value to a non-empty string, or nothing.\n *\n * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key\n * in the result, and the display text stamped into the payload. Rejecting objects is what each\n * of those wants: an object FK is a link that was already expanded, and an object display column\n * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it\n * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.\n */\nfunction scalarText(value: unknown): string | undefined {\n\tif (value == null || typeof value === 'object') return undefined\n\tif (typeof value === 'string') return value === '' ? undefined : value\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn undefined\n}\n\nfunction collectLinkDisplaySpecs(meta: DoctypeMeta): LinkDisplaySpec[] {\n\tconst specs: LinkDisplaySpec[] = []\n\n\tfor (const field of flattenFields(meta.fields)) {\n\t\tif (field.kind !== 'field' || !field.doctype) continue\n\n\t\tconst targetMeta = getMeta(field.doctype)\n\t\tif (!targetMeta) continue\n\n\t\t// `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`\n\t\t// makes at the load gate, so a nomination that parsed is one this can build a SELECT from.\n\t\t// A hand-rolled scan here admitted `computed` fields, whose column does not exist.\n\t\tconst displayField = getDisplayField(targetMeta.fields, targetMeta.displayField)\n\t\tif (!displayField) continue\n\n\t\tspecs.push({\n\t\t\tfieldname: field.fieldname,\n\t\t\tdisplayField: displayField.fieldname,\n\t\t\ttargetPkFieldname: getRecordIdField(targetMeta.fields),\n\t\t\ttargetDoctype: targetMeta.name,\n\t\t})\n\t}\n\n\treturn specs\n}\n\n/**\n * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a\n * `displayField`. Expanded relations (object values) are skipped.\n *\n * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch\n * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the\n * loader exists to prevent, and does so invisibly, since the result is identical either way.\n */\nexport async function enrichLinkDisplayFields(\n\tpgClient: PgClient,\n\tmeta: DoctypeMeta,\n\trows: Record<string, unknown>[],\n\tcolumns: ColumnReader,\n\tdebugSql: SqlQueryFn\n): Promise<void> {\n\tconst specs = collectLinkDisplaySpecs(meta)\n\tif (specs.length === 0 || rows.length === 0) return\n\n\tawait Promise.all(\n\t\tspecs.map(async spec => {\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = scalarText(row[spec.fieldname])\n\t\t\t\tif (id !== undefined) ids.add(id)\n\t\t\t}\n\t\t\tif (ids.size === 0) return\n\n\t\t\tconst pkColumn = camelToSnake(spec.targetPkFieldname)\n\t\t\tconst select = columns.select(spec.targetDoctype, [\n\t\t\t\t{ column: pkColumn, alias: spec.targetPkFieldname },\n\t\t\t\t{ column: camelToSnake(spec.displayField), alias: spec.displayField },\n\t\t\t])\n\n\t\t\tconst { rows: displayRows } = await debugSql(pgClient, {\n\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\tvalues: [Array.from(ids)],\n\t\t\t})\n\t\t\tselect.decodeRows(displayRows)\n\n\t\t\tconst displayById = new Map<string, string>()\n\t\t\tfor (const displayRow of displayRows) {\n\t\t\t\tconst key = scalarText(displayRow[spec.targetPkFieldname])\n\t\t\t\tconst text = scalarText(displayRow[spec.displayField])\n\t\t\t\tif (key === undefined || text === undefined) continue\n\t\t\t\tdisplayById.set(key, text)\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst rawId = row[spec.fieldname]\n\t\t\t\tconst idKey = scalarText(rawId)\n\t\t\t\tif (idKey === undefined) continue\n\t\t\t\tconst displayText = displayById.get(idKey)\n\t\t\t\tif (displayText === undefined) continue\n\t\t\t\trow[spec.fieldname] = { id: rawId, displayText }\n\t\t\t}\n\t\t})\n\t)\n}\n","import { gql } from 'postgraphile/utils'\n\n/**\n * GraphQL type definitions for Stonecrop's middleware API.\n * Includes stonecropMeta, stonecropRecord, stonecropRecords, stonecropAction, and related types.\n * @public\n */\nexport const typeDefs = gql`\n\ttype StonecropFieldMeta {\n\t\tkind: String!\n\t\tfieldname: String!\n\t\tcomponent: String\n\t\tprimaryKey: Boolean\n\t\tcomputed: Boolean\n\t\tlanguage: String\n\t\tdoctype: String\n\t\tlabel: String\n\t\twidth: String\n\t\theight: String\n\t\talign: String\n\t\tedit: Boolean\n\t\tmask: String\n\t\tformat: String\n\t\tmode: String\n\t\toptions: JSON\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\tvalidation: JSON\n\t\tcardinality: String\n\t\tsource: String\n\t\tconfig: JSON\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tnextState: String\n\t\tstateless: Boolean\n\t\tselfTransition: Boolean\n\t\tclientHandler: String\n\t}\n\n\ttype StonecropWorkflowMeta {\n\t\tstates: [String!]\n\t\tactions: [StonecropWorkflowAction!]\n\t}\n\n\ttype StonecropDoctypeMeta {\n\t\tname: String!\n\t\tslug: String\n\t\tdisplayField: String\n\t\tfields: [StonecropFieldMeta!]!\n\t\tworkflow: StonecropWorkflowMeta\n\t\tinherits: String\n\t}\n\n\ttype StonecropRecordResult {\n\t\tdata: JSON\n\t\tdoctype: String!\n\t\tunknownLinks: [String!]\n\t\t\"\"\"\n\t\tFields whose linked rows were cut short by a row cap, so data holds a prefix of the\n\t\trelation rather than all of it. Null when nothing was truncated. A link cannot be paged,\n\t\tso a client that sees a name here must not write that relation back — the rows it never\n\t\treceived would be deleted.\n\t\t\"\"\"\n\t\ttruncatedLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\t\"\"\"\n\t\tWhether further records exist beyond this page. Always answered — it is read from the\n\t\tpage itself (one extra row is requested and discarded), so it costs no second query.\n\t\t\"\"\"\n\t\thasMore: Boolean!\n\t\t\"\"\"\n\t\tTotal matching the filters, ignoring limit/offset. Null unless the query asked for it\n\t\twith includeTotal, because counting is a full scan on most backends.\n\t\t\"\"\"\n\t\tcount: Int\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\t\"\"\"\n\t\tWhat the action's registered handler returned, verbatim, or the outcome the doctype declared.\n\t\t\"\"\"\n\t\tdata: JSON\n\t\terror: String\n\t\t\"\"\"\n\t\tThe record as stonecropRecord returns it after the action, whoever wrote it. The client stores\n\t\tthis, never data. Null when the action failed or targets no record.\n\t\t\"\"\"\n\t\trecord: JSON\n\t\t\"\"\"\n\t\tKeys the write discarded because the doctype declares no column for them, or because the\n\t\tvalue was a nested relation rather than a column value. Null when everything sent was\n\t\tstored. The action still succeeded — this is what it did not keep, and a client that\n\t\treports an unqualified success without checking it tells the user data was saved that\n\t\twas not.\n\t\t\"\"\"\n\t\tdroppedFields: [String!]\n\t}\n\n\textend type Query {\n\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\tstonecropRecord(doctype: String!, id: String!, options: JSON): StonecropRecordResult\n\t\tstonecropRecords(\n\t\t\tdoctype: String!\n\t\t\tfilters: JSON\n\t\t\torderBy: String\n\t\t\tlimit: Int\n\t\t\toffset: Int\n\t\t\tincludeTotal: Boolean\n\t\t\toptions: JSON\n\t\t): StonecropRecordsResult\n\t}\n\n\textend type Mutation {\n\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t}\n`\n","import type { DoctypeField, DoctypeMeta, LinkDeclaration, ValueField, GetRecordOptions } from '@stonecrop/schema'\nimport { camelToSnake, getRecordIdField, resolveLinkRenderMode, unwrapInlineLinks } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgCodec, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { createColumnReader } from '../columns'\nimport type { ColumnSelection } from '../columns'\nimport { columnBackedFields, flattenFields } from '../fields'\nimport { enrichLinkDisplayFields } from '../link-display'\nimport { resolveTableName } from '../tables'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta, validateReferences } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Everything a server-side action handler is given when `stonecropAction` dispatches to it.\n *\n * A context object rather than positional parameters so the set can grow without breaking\n * registered handlers — the adapters that supply these live in consumer repositories.\n * @public\n */\nexport interface ActionHandlerContext {\n\t/**\n\t * Active database client for the current request. **It is inside the action's transaction.**\n\t *\n\t * The guard read, this handler, and the state write all run on this client inside one\n\t * transaction, so the action is atomic: throw, and everything this handler wrote is rolled\n\t * back along with the state change. Returning normally commits the lot.\n\t *\n\t * Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would\n\t * close the action's transaction early, committing work the guard may still reject. If you\n\t * need to undo part of your own work without failing the action, use a `SAVEPOINT`.\n\t *\n\t * Work sent to a *different* connection is outside all of this and will not be rolled back —\n\t * so use this client rather than opening one of your own.\n\t *\n\t * Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's\n\t * own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that\n\t * returns raw rows therefore leaks snake_case keys to the client. Alias in SQL\n\t * (`\"display_name\" AS \"displayName\"`) or convert with `snakeToCamel` from `@stonecrop/schema`.\n\t */\n\tpgClient: PgClient\n\t/** The doctype the action was dispatched against, as the client sent it. */\n\tdoctype: string\n\t/** The action's key in `workflow.actions` — the same string the handler was registered under. */\n\taction: string\n\t/** The resolved doctype metadata, for field names, the primary key, and the workflow. */\n\tmeta: DoctypeMeta\n\t/** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */\n\trecordId?: string | number\n\t/**\n\t * The record field data the client sent (`args[0].data`).\n\t *\n\t * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has\n\t * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist\n\t * the fields the action is allowed to touch.\n\t */\n\tdata: Record<string, unknown>\n\t/** The full argument envelope, for the actions that need more than the first record. */\n\targs: unknown[]\n\t/** The state the guard read, or `undefined` when nothing about the action required reading it. */\n\tcurrentState?: string\n}\n\n/**\n * A server-side effect for one doctype action, supplied by whoever owns the database.\n *\n * Throwing rejects the action and no state is written. The client stores the result's `record`,\n * the adapter's read of the record after the action, never this return; a return carrying the\n * doctype's declared key names the record read, which is how a handler that creates one says so.\n *\n * The return value is passed through verbatim as `StonecropActionResult.data`, so it must be\n * API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and\n * ADR 0007.\n * @public\n */\nexport type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin.\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/**\n\t * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks\n\t * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.\n\t */\n\tdebug?: boolean\n\t/**\n\t * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.\n\t * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).\n\t * SQL fragments and subqueries are not supported.\n\t * When absent for a doctype, the table name is derived as `pascalToSnake(doctype.name)`, so\n\t * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a\n\t * PascalCase name: `camelToSnake('User')` is `_user`.)\n\t */\n\ttables?: Record<string, string>\n\t/**\n\t * Server-side effects for workflow actions, keyed `[doctype name][action key]`.\n\t *\n\t * This is the seam that makes a stateless Command executable. `applyGuardedTransition` can\n\t * apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —\n\t * but an action that is neither has nothing to apply and fails loudly. Registering a handler\n\t * here supplies the missing half.\n\t *\n\t * **The doctype never names a handler, and a handler never overrides the guard.** The two are\n\t * authored by different people: a doctype is runtime data edited in DocBuilder by whoever\n\t * models the workflow, while these run behind the GraphQL surface and belong to whoever owns\n\t * the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state\n\t * results), and this keeps the effect (what actually happens). Routing between them is\n\t * resolved here, on the server, and is never published to the client.\n\t *\n\t * Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An\n\t * unregistered action is not an error in itself: a transition needs no handler. It fails only\n\t * when the doctype gave the action no outcome either, and the error then names the action and\n\t * both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.\n\t *\n\t * @example\n\t * ```ts\n\t * createStonecropPlugin({\n\t * actionHandlers: {\n\t * Order: {\n\t * async recalculateTotal({ pgClient, recordId }) {\n\t * const { rows } = await pgClient.query({\n\t * text: 'UPDATE \"order\" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',\n\t * values: [recordId],\n\t * })\n\t * return rows[0]\n\t * },\n\t * },\n\t * },\n\t * })\n\t * ```\n\t */\n\tactionHandlers?: Record<string, Record<string, ActionHandler>>\n\t/**\n\t * Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests\n\t * no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults\n\t * to 200.\n\t *\n\t * A row cap is a statement about what this database can afford to serve, so it belongs to\n\t * whoever owns the database — not to a doctype (which describes the API surface, not the\n\t * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay\n\t * free to ask for less; they cannot ask for an unbounded scan by omission.\n\t *\n\t * One number covers both reads because a link *is* a list, fetched a different way. It used to\n\t * be capped at a hard-coded 50 that no option could reach, which is how an operator watching a\n\t * slow query found there was no knob to turn.\n\t *\n\t * Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a\n\t * partial answer is distinguishable from a complete one without asking for a count. That\n\t * matters more for a link than for a list: a link cannot be paged, so a client that writes\n\t * back a truncated relation deletes the rows it was never sent.\n\t *\n\t * Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an\n\t * unqualified list query returns the whole table and a link returns the whole relation.\n\t */\n\tdefaultRecordLimit?: number | null\n}\n\n/**\n * Carries a reported failure out through a `throw`, purely so the transaction rolls back.\n *\n * `applyGuardedTransition` reports every failure as a return value, and a value returned from\n * inside `withTransaction` commits. This is the adapter between \"the action failed\" and \"undo it\"\n * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and\n * answers with the original envelope.\n */\nclass ActionRolledBack extends Error {\n\tconstructor(readonly outcome: { success: boolean; data: unknown; error: string | null }) {\n\t\tsuper(outcome.error ?? 'Action failed')\n\t\tthis.name = 'ActionRolledBack'\n\t}\n}\n\n/** One record a read is asked for: the arguments `stonecropRecord` takes. */\ninterface RecordReadSpec {\n\tdoctype: unknown\n\tid: unknown\n\toptions?: unknown\n}\n\n/** One record as `stonecropRecord` serves it. */\ninterface RecordReadResult {\n\tdata: Record<string, unknown> | null\n\tdoctype: string\n\tunknownLinks?: string[]\n\ttruncatedLinks?: string[]\n}\n\n/**\n * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can\n * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getColumnSelections`\n * omits its FK column by design — but the expansion needs the value to find the target. Aliasing\n * keeps that need from changing the payload: every alias is stripped before the record is returned.\n */\nconst LINK_FK_ALIAS = '__stonecropLinkFk_'\n\n/**\n * The column this adapter keeps a record's workflow state in.\n *\n * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,\n * the transition's write, and the data write that must refuse to touch it. A patch that could set\n * this column would let any client walk past `allowedStates` by writing the very value the guard\n * reads.\n */\nconst STATE_COLUMN = 'status'\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.\n *\n * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`\n * during schema construction — it does not need to be supplied by the caller.\n *\n * @param options - Optional plugin configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions = {}): GraphileConfig.Plugin => {\n\t/**\n\t * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging\n\t * for queries that run inside custom loadOneWithPgClient callbacks, which\n\t * bypass the executor's native instrumentation.\n\t */\n\tconst debugSql = options.debug\n\t\t? <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? [])\n\t\t\t\treturn pgClient.query<T>(query)\n\t\t\t}\n\t\t: <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => pgClient.query<T>(query)\n\n\t// Resolved once, for both read paths. `undefined` means \"not configured\" and `null` means\n\t// \"configured off\", which is a distinction `??` cannot make — and the two paths disagreeing\n\t// about it is exactly how a link came to be capped by a different number than a list.\n\tconst defaultRowLimit: number | null = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit\n\n\tconst schemaPlugin = extendSchema(build => {\n\t\t// Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type\n\t\tconst pgRegistry = (build as any).input?.pgRegistry as\n\t\t\t| { pgExecutors?: Record<string, PgExecutor>; pgCodecs?: Record<string, PgCodec> }\n\t\t\t| undefined\n\t\tconst executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : undefined\n\t\tif (!executor) {\n\t\t\tthrow new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured')\n\t\t}\n\t\tconst columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables)\n\n\t\t// Schema build is the one point where both the registry and the plugin's options are in\n\t\t// hand, so it is where a stale registration can be caught before it silently no-ops.\n\t\tif (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers)\n\t\tassertReferencesResolve()\n\n\t\t/** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */\n\t\tconst readRecords = async (pgClient: PgClient, specs: readonly RecordReadSpec[]): Promise<RecordReadResult[]> => {\n\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t}\n\n\t\t\tconst results: RecordReadResult[] = Array.from({ length: specs.length })\n\n\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\tif (!meta) {\n\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Not `data: null` — that is the answer for a record that does not exist, and a\n\t\t\t\t// doctype nobody can look up is a misconfiguration, not an empty result.\n\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(doctype)\n\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t// Resolved once per doctype: how each link renders, and which foreign keys the\n\t\t\t\t// SELECT must carry for the expansion below to work at all.\n\t\t\t\t//\n\t\t\t\t// `resolveLinkRenderMode` needs the linked field's own component, so the fields\n\t\t\t\t// are indexed by name — flattened, because a link's field may sit inside a\n\t\t\t\t// fieldset and `getColumnSelections` already descends to select it.\n\t\t\t\tconst fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]))\n\t\t\t\tconst linkFkAliases: Array<{ fieldname: string; alias: string }> = []\n\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links ?? {})) {\n\t\t\t\t\t// Many-side links find their rows by a column on the *target*; only a one-side\n\t\t\t\t\t// link reads a foreign key off this row.\n\t\t\t\t\tif (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') continue\n\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t// An inline link keeps its FK as a scalar, so `getColumnSelections` already selected\n\t\t\t\t\t// it under its own name and no alias is needed.\n\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\t\t\t\t\tlinkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` })\n\t\t\t\t}\n\t\t\t\tconst select = columns.select(meta.name, [\n\t\t\t\t\t...getColumnSelections(meta),\n\t\t\t\t\t...linkFkAliases.map(({ fieldname, alias }) => ({ column: camelToSnake(fieldname), alias })),\n\t\t\t\t])\n\n\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\tvalues: [ids],\n\t\t\t\t})\n\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t// A declared key the database does not actually enforce as unique collapses several\n\t\t\t\t// rows into that Map, and it keeps whichever came last — one arbitrary record,\n\t\t\t\t// returned as though it were *the* record, with nothing to say so. Refuse instead.\n\t\t\t\t//\n\t\t\t\t// This is exact rather than a proxy for the problem: `ANY` matches each requested id\n\t\t\t\t// once, so a shortfall here means two distinct rows genuinely share a key value. A\n\t\t\t\t// `pg_index` check would instead ask whether a unique constraint exists, which is the\n\t\t\t\t// cause rather than the harm — and would flag a column that is unique in practice but\n\t\t\t\t// unconstrained, which is a real and common shape.\n\t\t\t\tif (rows.length !== rowByPk.size) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Doctype \"${doctype}\" declares \"${pkMeta.fieldname}\" as its identity, but that column ` +\n\t\t\t\t\t\t\t`is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +\n\t\t\t\t\t\t\t`matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +\n\t\t\t\t\t\t\t`Declare a field that uniquely identifies a record, or add a unique constraint.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Collected across the batch so the display lookup runs once for all of them.\n\t\t\t\t// Called per row inside this loop it issued one query per record per link field,\n\t\t\t\t// which is the N+1 this batched loader exists to avoid — and silently, since the\n\t\t\t\t// enriched rows come out identical either way.\n\t\t\t\tconst enrichedRows: Record<string, unknown>[] = []\n\n\t\t\t\tfor (const i of indices) {\n\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\tenrichedRows.push(rowData)\n\t\t\t\t\t// Per record, not per doctype: two records of one doctype can differ in whether\n\t\t\t\t\t// a relation overflowed, and a shared list would report the wrong one truncated.\n\t\t\t\t\tconst truncatedLinks: string[] = []\n\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null\n\n\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t// The payload key is the *resolved* fieldname, not the map key: the client\n\t\t\t\t\t\t\t// binds a link to the field named `link.fieldname ?? key` and reads the\n\t\t\t\t\t\t\t// nested data off that field, so writing under the bare key put the result\n\t\t\t\t\t\t\t// somewhere nothing looks whenever a declaration named its own `fieldname`.\n\t\t\t\t\t\t\t// Identical for every declaration that omits `fieldname`, which is all of them\n\t\t\t\t\t\t\t// in this repo — hence latent until now.\n\t\t\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t// Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only\n\t\t\t\t\t\t\t// `SyncFetch` carries a `limit` — and the server default used to hang off its\n\t\t\t\t\t\t\t// `else`, so declaring the method a many-side link already defaults to removed\n\t\t\t\t\t\t\t// the cap entirely. \"Did the author write a limit?\" and \"did the author write\n\t\t\t\t\t\t\t// the word sync?\" are now asked separately.\n\t\t\t\t\t\t\tconst declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined\n\t\t\t\t\t\t\tconst effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined\n\n\t\t\t\t\t\t\t// The one gate. It used to be followed by a second test that re-asked the\n\t\t\t\t\t\t\t// same question using only `includeSet` — `null` for the boolean form — so\n\t\t\t\t\t\t\t// `includeNested: true` admitted every link here and then silently dropped\n\t\t\t\t\t\t\t// each non-`sync` one, handing back a partial record with no way to tell.\n\t\t\t\t\t\t\t// That test was redundant wherever it was correct: with a name list this gate\n\t\t\t\t\t\t\t// has already required membership, and without one it has already required\n\t\t\t\t\t\t\t// `sync`, so it could only ever fire in the boolean case it got wrong.\n\t\t\t\t\t\t\tconst shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\t\t\t// TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above\n\t\t\t\t\t\t\t\t\trowData[fieldname] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// `resolveLinkRenderMode` is the single definition of whether a link expands,\n\t\t\t\t\t\t\t// and this loop was the one caller that never asked it. An `inline` link is a\n\t\t\t\t\t\t\t// picker: the field holds its own id and the client resolves display text\n\t\t\t\t\t\t\t// separately, so expanding it here overwrote that id with the whole target\n\t\t\t\t\t\t\t// record and left the picker with an object it cannot render.\n\t\t\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\n\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\tconst targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta))\n\n\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t// Same reason the list path orders: a capped relation without a fixed order\n\t\t\t\t\t\t\t\t// returns an arbitrary subset of the children, and a different one each time\n\t\t\t\t\t\t\t\t// a child row is updated. `truncatedLinks` says the tail was cut; it cannot\n\t\t\t\t\t\t\t\t// say the head kept changing. Skipped when the target declares no identity —\n\t\t\t\t\t\t\t\t// there is no stable key to order by, and inventing one would be a guess.\n\t\t\t\t\t\t\t\tconst linkPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (linkPkMeta) {\n\t\t\t\t\t\t\t\t\tsql += ` ORDER BY \"${camelToSnake(linkPkMeta.fieldname)}\" ASC`\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t// One row more than the cap, same probe the list path uses: its presence\n\t\t\t\t\t\t\t\t\t// is the whole truncation answer and costs no second query.\n\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above\n\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\t// A truncated relation that says nothing is how a read-modify-write deletes\n\t\t\t\t\t\t\t\t// the tail: the client cannot tell 50 rows from all of them, so it writes\n\t\t\t\t\t\t\t\t// back what it was given. Reported for every source of truncation, the\n\t\t\t\t\t\t\t\t// author's `fetch.limit` included — that one is just as silent.\n\t\t\t\t\t\t\t\tif (effectiveLimit != null && linked.length > effectiveLimit) {\n\t\t\t\t\t\t\t\t\ttruncatedLinks.push(fieldname)\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read from the reserved alias, never the fieldname: an expanding link's FK\n\t\t\t\t\t\t\t\t// column is deliberately absent from `getColumnSelections`, so the plain read found\n\t\t\t\t\t\t\t\t// `undefined` on every record and answered `null` — a relation that looked\n\t\t\t\t\t\t\t\t// permanently empty rather than one nobody had asked the right question for.\n\t\t\t\t\t\t\t\tconst fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`]\n\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = null\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// `continue` here would drop the link from the payload, which reads to the\n\t\t\t\t\t\t\t\t// client as \"this record has no such relation\" rather than \"its target\n\t\t\t\t\t\t\t\t// cannot be identified\".\n\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name)\n\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\t\t// TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above\n\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\trowData[fieldname] = linked[0] ?? null\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The aliases are a read channel for this loop, not part of the record. Stripped\n\t\t\t\t\t// unconditionally so a link that was never expanded cannot leak its raw FK into a\n\t\t\t\t\t// payload that has otherwise always described that relation as a nested object.\n\t\t\t\t\tfor (const { alias } of linkFkAliases) delete rowData[alias]\n\n\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\ttruncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// After the expansion loop, not before it: a link that expanded has replaced its\n\t\t\t\t// scalar FK with an object, and enrichment skips those. Running first stamped a\n\t\t\t\t// display value beside a relation that no longer had an id to display.\n\t\t\t\t//\n\t\t\t\t// Sequential per doctype group because `pgClient` is one checked-out connection,\n\t\t\t\t// so awaiting these together would only queue them inside the driver.\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop\n\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql)\n\t\t\t}\n\n\t\t\treturn results\n\t\t}\n\n\t\treturn {\n\t\t\ttypeDefs,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(String(doctype))\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id, $options }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, id: $id, options: $options }),\n\t\t\t\t\t\t\t\treadRecords\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t\tincludeTotal: $includeTotal,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst doctype = String(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\t// An unknown doctype answers \"no records\" rather than erroring, so a caller\n\t\t\t\t\t\t\t\t\t\t\t\t// who asked for a total gets 0. Returning null here would make null mean\n\t\t\t\t\t\t\t\t\t\t\t\t// two things — \"you did not ask\" and \"I could not say\" — and a client\n\t\t\t\t\t\t\t\t\t\t\t\t// cannot tell those apart.\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null }\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname))\n\t\t\t\t\t\t\t\t\t\t\tconst select = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection). Built once for\n\t\t\t\t\t\t\t\t\t\t\t// the page and its total, which must count the rows the page is drawn from.\n\t\t\t\t\t\t\t\t\t\t\tconst filterValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\tconst whereClauses: string[] = []\n\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown filter field: ${field} for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tfilterValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst column = camelToSnake(field)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`\"${column}\" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = [...filterValues]\n\n\t\t\t\t\t\t\t\t\t\t\t// ORDER BY (field name whitelisted — column names cannot be parameterised)\n\t\t\t\t\t\t\t\t\t\t\tlet orderByClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (typeof spec.orderBy !== 'string')\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`)\n\t\t\t\t\t\t\t\t\t\t\t\tconst orderByStr = spec.orderBy\n\t\t\t\t\t\t\t\t\t\t\t\tconst lastUnder = orderByStr.lastIndexOf('_')\n\t\t\t\t\t\t\t\t\t\t\t\tif (lastUnder <= 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy format: \"${orderByStr}\". Expected FIELD_ASC or FIELD_DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst dir = orderByStr.slice(lastUnder + 1).toUpperCase()\n\t\t\t\t\t\t\t\t\t\t\t\tif (dir !== 'ASC' && dir !== 'DESC') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy direction: \"${dir}\". Must be ASC or DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst fieldName = orderByStr.slice(0, lastUnder)\n\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(fieldName)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown orderBy field: \"${fieldName}\" for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(fieldName)}\" ${dir}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// A page is only meaningful against a fixed order, and LIMIT/OFFSET without one\n\t\t\t\t\t\t\t\t\t\t\t// is two independent scans of heap order — an UPDATE between them moves that row\n\t\t\t\t\t\t\t\t\t\t\t// to the tail, so the row it displaced is never returned and nothing in the\n\t\t\t\t\t\t\t\t\t\t\t// payload says a record was skipped. The declared identity is the right default\n\t\t\t\t\t\t\t\t\t\t\t// because it is unique: it gives a total order, which is what makes page 2 start\n\t\t\t\t\t\t\t\t\t\t\t// exactly where page 1 stopped.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Only when the doctype declares an identity. Without one there is no stable key\n\t\t\t\t\t\t\t\t\t\t\t// to order by, and inventing one here would be a guess; such a doctype cannot be\n\t\t\t\t\t\t\t\t\t\t\t// paged stably by any means.\n\t\t\t\t\t\t\t\t\t\t\tif (orderByClause === '') {\n\t\t\t\t\t\t\t\t\t\t\t\tconst listPkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\t\t\tif (listPkMeta) {\n\t\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(listPkMeta.fieldname)}\" ASC`\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// LIMIT / OFFSET. A caller that names no limit gets the configured default rather\n\t\t\t\t\t\t\t\t\t\t\t// than the whole table: omission is how an unbounded scan used to happen, and the\n\t\t\t\t\t\t\t\t\t\t\t// only guard against it lived in the scaffold's fetch helper, which is neither the\n\t\t\t\t\t\t\t\t\t\t\t// right layer nor present in a host that wrote its own.\n\t\t\t\t\t\t\t\t\t\t\t// Grafast passes arguments through as loosely-typed runtime values, so narrow\n\t\t\t\t\t\t\t\t\t\t\t// before doing arithmetic on this — same reason orderBy is validated above.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null && typeof spec.limit !== 'number') {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid limit: expected number, got ${typeof spec.limit}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit: number | null = spec.limit ?? defaultRowLimit\n\t\t\t\t\t\t\t\t\t\t\tlet pagingClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// One more row than asked for. Its presence is the whole `hasMore` answer, and\n\t\t\t\t\t\t\t\t\t\t\t\t// it is discarded below — this is why knowing a list is truncated costs no\n\t\t\t\t\t\t\t\t\t\t\t\t// second query, where a COUNT(*) would be a full scan on every list read.\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` LIMIT $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.offset)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` OFFSET $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t\t\t\t\t\t\t\t// The extra row requested above is a probe, not data. Its presence is what makes\n\t\t\t\t\t\t\t\t\t\t\t// a capped page distinguishable from a complete table; trim it before anything\n\t\t\t\t\t\t\t\t\t\t\t// downstream can mistake it for a record.\n\t\t\t\t\t\t\t\t\t\t\tconst hasMore = effectiveLimit != null && rows.length > effectiveLimit\n\t\t\t\t\t\t\t\t\t\t\tconst data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)]\n\n\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql)\n\n\t\t\t\t\t\t\t\t\t\t\t// Total matching the filters, independent of LIMIT/OFFSET, and opt-in.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Explicitly requested rather than inferred from whether `count` was selected:\n\t\t\t\t\t\t\t\t\t\t\t// this resolver is a Grafast plan step and receives only its arguments, never the\n\t\t\t\t\t\t\t\t\t\t\t// selection set, and making the plan vary by selection is what Grafast optimises\n\t\t\t\t\t\t\t\t\t\t\t// against. An argument also puts the cost in the query the client wrote.\n\t\t\t\t\t\t\t\t\t\t\tlet count: number | null = null\n\t\t\t\t\t\t\t\t\t\t\tif (spec.includeTotal === true) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: countRows } = await debugSql<{ row_count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: filterValues,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\tcount = parseInt(countRows[0]?.row_count ?? '0', 10)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\treturn { data, doctype, hasMore, count }\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn sideEffectWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, action: $action, actionArgs: $actionArgs }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, spec: any) => {\n\t\t\t\t\t\t\t\t\tconst meta = getMeta(String(spec.doctype))\n\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Resolved lazily: only a state read or write needs the key column. A\n\t\t\t\t\t\t\t\t\t// record-less command reaches its handler on a doctype that declares no\n\t\t\t\t\t\t\t\t\t// primary key, which an eager check would refuse for no reason.\n\t\t\t\t\t\t\t\t\tconst pkColumn = () => {\n\t\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(String(spec.doctype))\n\t\t\t\t\t\t\t\t\t\treturn camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// Record envelope: [{ id, data }] — the transition keys off the record id.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract\n\t\t\t\t\t\t\t\t\tconst rawArgs = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []) as Array<{\n\t\t\t\t\t\t\t\t\t\tid?: string | number\n\t\t\t\t\t\t\t\t\t\tdata?: Record<string, unknown>\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\t// An inline link arrives as `{ id, displayText }`; a column takes the id alone.\n\t\t\t\t\t\t\t\t\t// Reduced here so no client has to know what storage accepts.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The whole envelope, not just `recordData` below — handlers read `ctx.args`.\n\t\t\t\t\t\t\t\t\t// Copied, not mutated: `spec.actionArgs` is the request's own value.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line oxc/no-map-spread\n\t\t\t\t\t\t\t\t\tconst argList = rawArgs.map(entry =>\n\t\t\t\t\t\t\t\t\t\tentry?.data ? { ...entry, data: unwrapInlineLinks(meta.fields, entry.data) } : entry\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tconst recordId = argList[0]?.id\n\t\t\t\t\t\t\t\t\tconst recordData = argList[0]?.data ?? {}\n\n\t\t\t\t\t\t\t\t\t// The database author's effect for this action, if one is registered. Keyed\n\t\t\t\t\t\t\t\t\t// by the doctype's canonical name so a slug-resolved lookup above cannot\n\t\t\t\t\t\t\t\t\t// silently miss it.\n\t\t\t\t\t\t\t\t\tconst handler = options.actionHandlers?.[meta.name]?.[String(spec.action)]\n\n\t\t\t\t\t\t\t\t\t// What a data write is allowed to set. Column identifiers come from the\n\t\t\t\t\t\t\t\t\t// doctype and never from the request — `args` is an opaque JSON scalar, so\n\t\t\t\t\t\t\t\t\t// every key in `data` is browser-supplied — which is what makes it safe to\n\t\t\t\t\t\t\t\t\t// build SQL from a patch at all.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The same derivation the read path uses, so what a record exposes is what a\n\t\t\t\t\t\t\t\t\t// record accepts. `status` is removed because state is the workflow's to\n\t\t\t\t\t\t\t\t\t// move, never the patch's. A column the database fills itself is refused in\n\t\t\t\t\t\t\t\t\t// `partitionPatch`, which asks the table only when there is a row to write:\n\t\t\t\t\t\t\t\t\t// this map is built for every action, including one on a doctype with no table.\n\t\t\t\t\t\t\t\t\tconst writable = new Map(\n\t\t\t\t\t\t\t\t\t\tcolumnBackedFields(meta.fields)\n\t\t\t\t\t\t\t\t\t\t\t.filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)\n\t\t\t\t\t\t\t\t\t\t\t.map(f => [f.fieldname, f] as const)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Whether this doctype has a workflow state to read at all. Derived from the\n\t\t\t\t\t\t\t\t\t// same declarations, so the guard cannot look for a column the doctype's own\n\t\t\t\t\t\t\t\t\t// API surface does not describe.\n\t\t\t\t\t\t\t\t\tconst declaresState = columnBackedFields(meta.fields).some(\n\t\t\t\t\t\t\t\t\t\tf => camelToSnake(f.fieldname) === STATE_COLUMN\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Reported on the result rather than logged: a dropped key is data the user\n\t\t\t\t\t\t\t\t\t// believes was saved, which is the same data-loss signal `truncatedLinks`\n\t\t\t\t\t\t\t\t\t// carries for a truncated read.\n\t\t\t\t\t\t\t\t\tconst droppedFields: string[] = []\n\t\t\t\t\t\t\t\t\tconst partitionPatch = (patch: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\t\t\tconst cols: string[] = []\n\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\t\t\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\t\t\t\t\t\t\tif (!writable.has(key) || !columns.writable(meta.name, camelToSnake(key))) {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// An expanding link reads back as a nested record while its column\n\t\t\t\t\t\t\t\t\t\t\t// holds a scalar foreign key, so a read-modify-write hands this loop\n\t\t\t\t\t\t\t\t\t\t\t// an object bound for a uuid column. The name resolving is not\n\t\t\t\t\t\t\t\t\t\t\t// enough; the shape has to match a column value too.\n\t\t\t\t\t\t\t\t\t\t\tif (value !== null && typeof value === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcols.push(camelToSnake(key))\n\t\t\t\t\t\t\t\t\t\t\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn { cols, values }\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// One transaction spans the guard read, the effect and the state write, so an\n\t\t\t\t\t\t\t\t\t// action either lands whole or not at all. `withTransaction` issues `begin` at\n\t\t\t\t\t\t\t\t\t// the top level and a `savepoint` if something upstream already opened one, so\n\t\t\t\t\t\t\t\t\t// nesting is safe rather than something callers must avoid.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// Every statement below runs on `tx`, not on the outer client. Work sent to the\n\t\t\t\t\t\t\t\t\t// outer client — or to a connection a handler opens itself — is outside this\n\t\t\t\t\t\t\t\t\t// transaction and would survive a rollback.\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await pgClient.withTransaction(async (tx: PgClient) => {\n\t\t\t\t\t\t\t\t\t\t\tconst outcome = await applyGuardedTransition(\n\t\t\t\t\t\t\t\t\t\t\t\tactionDef,\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No id in the envelope means no record was targeted at all, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the same answer as a lookup that misses: `null`, not `undefined`.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Selecting `status` unconditionally made this read fail outright on\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// any table without that column — and a self-transition reaches here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// not to read a state but to learn whether the row exists, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// what decides create vs. update. So the projection follows the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// doctype: a doctype that declares no state field has none to read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and the honest answer for a row it finds is \"exists, no state\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (Measured: 24 of FAB's 35 guarded tables have no `status` column.)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst projection = declaresState ? `\"${STATE_COLUMN}\"` : `\"${pkColumn()}\"`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FOR UPDATE holds the row until this transaction ends, so a second\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// action on the same record waits rather than reading the same state\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and acting on it too. Without it the guard is a check-then-act\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// race: two concurrent approvals both read PENDING and both proceed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, string | null>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${projection} FROM ${table} WHERE \"${pkColumn()}\"::text = $1 FOR UPDATE`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (rows.length === 0) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!declaresState) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0][STATE_COLUMN] ?? undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"${STATE_COLUMN}\" = $1 WHERE \"${pkColumn()}\"::text = $2`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [nextState, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t// The upsert, and the only write path for record data. `exists`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// comes from the guard's own read, so no second lookup decides it.\n\t\t\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t\t\t// Returns the same projection the read path selects, never\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `RETURNING *`: raw columns come back snake_case, and the client\n\t\t\t\t\t\t\t\t\t\t\t\t\t// resolves identity by the *declared fieldname*. A doctype keyed\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `itemId` would receive `item_id`, find no identity, and file a\n\t\t\t\t\t\t\t\t\t\t\t\t\t// created record nowhere — which is that exact bug, already once\n\t\t\t\t\t\t\t\t\t\t\t\t\t// shipped and patched downstream.\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteData: async (patch: Record<string, unknown>, exists: boolean) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { cols, values } = partitionPatch(patch)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst returning = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Creating is what the *absence* of an id means. An id that was\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dispatched and matched nothing is a record that has gone away\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// since the client read it, and treating that as a create mints a\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// second row under a new identity while the client believes it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// updated the first — a lost update that reports success.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// The dispatcher cannot make this call: it never receives the id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// deliberately, since identity is the backend's business. So the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// distinction its `readState` contract collapses is restored here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// where the id is in scope.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Action \"${actionDef.label ?? spec.action}\" targets ${meta.name} \"${String(recordId)}\", ` +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`which no longer exists. Nothing was created — a record dispatched with an ` +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`identity is an update, and creating one is what dispatching no identity means.`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No identity is minted here. A declared key present in the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// patch is a natural key the user filled in and passes\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// through the whitelist like any other column; absent, the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// column default supplies it. Either way the row states its\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// own identity back.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst text = cols.length\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? `INSERT INTO ${table} (${cols.map(c => `\"${c}\"`).join(', ')}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(', ')}) RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, { text, values })\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Nothing writable survived the patch. `SET` with no assignments\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// is a syntax error, and reporting failure would be wrong — the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// record is fine, it just has no new data. Read it back so the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// client still gets the record, with `droppedFields` saying why\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// nothing changed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (cols.length === 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${returning.list} FROM ${table} WHERE \"${pkColumn()}\"::text = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst assignments = cols\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.map((c, i) => `\"${c}\" = ${columns.bind(meta.name, c, `$${i + 1}`)}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET ${assignments} WHERE \"${pkColumn()}\"::text = $${cols.length + 1} RETURNING ${returning.list}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [...values, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\trunEffect: handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (currentState: string | undefined) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thandler({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpgClient: tx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoctype: String(spec.doctype),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taction: String(spec.action),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trecordId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata: recordData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\targs: argList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentState,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t// The patch a self-transition persists. This adapter never passed it, which\n\t\t\t\t\t\t\t\t\t\t\t\t// was moot while it had no `writeData` — nothing consumed it. Wiring the write\n\t\t\t\t\t\t\t\t\t\t\t\t// without this argument saves an empty record and reports success.\n\t\t\t\t\t\t\t\t\t\t\t\trecordData\n\t\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t// `applyGuardedTransition` REPORTS failure, it does not throw — a refused\n\t\t\t\t\t\t\t\t\t\t\t// guard and a handler that blew up both come back as `{ success: false }`.\n\t\t\t\t\t\t\t\t\t\t\t// Returning that normally would commit the transaction, so a handler that\n\t\t\t\t\t\t\t\t\t\t\t// wrote three rows and then threw would keep all three. Throwing here is\n\t\t\t\t\t\t\t\t\t\t\t// what makes the rollback happen; the envelope is carried across so the\n\t\t\t\t\t\t\t\t\t\t\t// caller still gets `success: false` rather than a GraphQL error.\n\t\t\t\t\t\t\t\t\t\t\tif (!outcome.success) throw new ActionRolledBack(outcome)\n\t\t\t\t\t\t\t\t\t\t\t// A record a write returns is a record, so it carries the links a read\n\t\t\t\t\t\t\t\t\t\t\t// resolves. Enriching one path and not the other changes a record's\n\t\t\t\t\t\t\t\t\t\t\t// shape depending on how the client came by it: a link rendered its\n\t\t\t\t\t\t\t\t\t\t\t// display text until the record was saved, and its raw id from then\n\t\t\t\t\t\t\t\t\t\t\t// until the next full fetch. Nothing fails — the field just goes wrong.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Runs inside the transaction so the lookup sees the row just written,\n\t\t\t\t\t\t\t\t\t\t\t// and only on success, since a rolled-back action returns no record.\n\t\t\t\t\t\t\t\t\t\t\t// A result that is not a record at all — an effect's `{ state }` — has\n\t\t\t\t\t\t\t\t\t\t\t// no field the doctype declares as an inline link, so it is untouched.\n\t\t\t\t\t\t\t\t\t\t\tif (outcome.success && outcome.data !== null && typeof outcome.data === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\t// A predicate rather than an assertion: an element that is not an object has\n\t\t\t\t\t\t\t\t\t\t\t\t// no field to enrich, so dropping it is the honest answer.\n\t\t\t\t\t\t\t\t\t\t\t\tconst written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t(row: unknown): row is Record<string, unknown> => row !== null && typeof row === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(tx, meta, written, columns, debugSql)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// The record as a read returns it, whoever wrote it: the client files this,\n\t\t\t\t\t\t\t\t\t\t\t// never `data`, which stays the handler's own. Keyed by the declared identity\n\t\t\t\t\t\t\t\t\t\t\t// the reply states when it states one, since an action may create or re-key\n\t\t\t\t\t\t\t\t\t\t\t// the record, and by the dispatched id otherwise.\n\t\t\t\t\t\t\t\t\t\t\tconst pkField = getPkMeta(meta)?.fieldname\n\t\t\t\t\t\t\t\t\t\t\tconst repliedId: unknown =\n\t\t\t\t\t\t\t\t\t\t\t\tpkField !== undefined && outcome.data !== null && typeof outcome.data === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Reflect.get(outcome.data, pkField)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t\t\t\t\t\tconst readId = repliedId ?? recordId\n\t\t\t\t\t\t\t\t\t\t\tconst record =\n\t\t\t\t\t\t\t\t\t\t\t\treadId == null\n\t\t\t\t\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t: ((await readRecords(tx, [{ doctype: meta.name, id: readId }]))[0]?.data ?? null)\n\n\t\t\t\t\t\t\t\t\t\t\t// Attached here rather than carried through `applyGuardedTransition`:\n\t\t\t\t\t\t\t\t\t\t\t// which keys a backend can store is a storage question, and the\n\t\t\t\t\t\t\t\t\t\t\t// dispatcher is deliberately storage-agnostic. A failed action wrote\n\t\t\t\t\t\t\t\t\t\t\t// nothing, so the list is only meaningful on success.\n\t\t\t\t\t\t\t\t\t\t\tconst reply = { ...outcome, record }\n\t\t\t\t\t\t\t\t\t\t\treturn droppedFields.length ? { ...reply, droppedFields } : reply\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\tif (err instanceof ActionRolledBack) return err.outcome\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\n\treturn {\n\t\t...schemaPlugin,\n\t\tgather: {\n\t\t\thooks: {\n\t\t\t\t// Marks a column Postgres generates as neither insertable nor updatable, as PostGraphile\n\t\t\t\t// itself marks an identity generated always. PostGraphile reads `attgenerated` only into\n\t\t\t\t// `hasDefault`, which a plain default shares, so without this the data write cannot tell\n\t\t\t\t// the two apart. On the adapter's plugin rather than the preset, so it holds wherever the\n\t\t\t\t// write runs.\n\t\t\t\tpgCodecs_attribute(_info, event) {\n\t\t\t\t\tconst { attgenerated } = event.pgAttribute\n\t\t\t\t\tif (attgenerated == null || attgenerated === '') return\n\t\t\t\t\tevent.attribute.extensions ??= {}\n\t\t\t\t\tevent.attribute.extensions.isInsertable = false\n\t\t\t\t\tevent.attribute.extensions.isUpdatable = false\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Derive column selections from a flat field array.\n * Skips non-scalar fields (kind !== 'field'), `computed` fields\n * (no backing DB column), and *expanding* links\n * (relations fetched separately, not scalar columns on this table).\n */\nfunction collectColumns(fields: DoctypeField[], links: Map<string, LinkDeclaration>): ColumnSelection[] {\n\tconst columns: ColumnSelection[] = []\n\tfor (const f of columnBackedFields(fields)) {\n\t\t// Only an *expanding* link is a relation rather than a column. An inline link (a picker)\n\t\t// keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the\n\t\t// rule both sides of the wire share; never re-derive it here.\n\t\tconst link = links.get(f.fieldname)\n\t\tif (link && resolveLinkRenderMode(link, f.component) !== 'inline') continue\n\t\tcolumns.push({ column: camelToSnake(f.fieldname), alias: f.fieldname })\n\t}\n\treturn columns\n}\n\n/**\n * Derive the columns a record payload selects from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, and keeps\n * the fieldname as its alias so result rows carry API-layer keys.\n * Excludes `computed` fields (no backing DB column), Fieldset\n * containers (recursing into their children instead), and *expanding* links\n * (relations fetched separately). An inline link keeps its FK column here.\n *\n * Exported for unit testing (not re-exported from the package index).\n */\nexport function getColumnSelections(meta: DoctypeMeta): ColumnSelection[] {\n\tconst links = new Map<string, LinkDeclaration>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinks.set(link.fieldname ?? key, link)\n\t\t}\n\t}\n\treturn collectColumns(meta.fields, links)\n}\n\n/**\n * Resolve the declared field this doctype's records are looked up by.\n *\n * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the\n * client's record keying name the same field — including the `id` fallback, whose absence here\n * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the\n * client and refused outright by this adapter, so every fetch answered `null` and looked exactly\n * like a record that does not exist.\n *\n * Returns `undefined` only when the resolved name is not a declared field — a doctype with no\n * `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields\n * only, so the row map would key on a column the SELECT never returned and every lookup would miss\n * silently. Callers must say so rather than answer `null`.\n *\n * Descends into fieldsets, because both halves of the question already do — `getColumnSelections` selects\n * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this\n * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose\n * SELECT carried its own key column had no identity to look that column up by.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\tconst fieldname = getRecordIdField(meta.fields)\n\treturn flattenFields(meta.fields).find((f): f is ValueField => f.kind === 'field' && f.fieldname === fieldname)\n}\n\n/**\n * Assert that every registered action handler names a doctype and an action that exist.\n *\n * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler\n * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.\n * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it\n * has one, the missing effect is skipped and the state write still reports success. So renaming a\n * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.\n *\n * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a\n * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a\n * real doctype here and still never fires. It is reported as its own case rather than as \"unknown\n * doctype\", because the repair is different.\n *\n * Throws rather than warns: there is no legitimate reason to register a handler for an action that\n * does not exist, and the alternative is a silent half-executed workflow. Every offender is\n * collected so a consumer with several fixes them in one pass.\n */\nfunction assertActionHandlersResolve(actionHandlers: Record<string, Record<string, ActionHandler>>): void {\n\t// Nothing registered, nothing to check.\n\tconst registered = Object.entries(actionHandlers)\n\tif (registered.length === 0) return\n\n\t// An empty registry cannot tell \"this key is stale\" from \"doctypes have not loaded yet\" — a\n\t// host is free to build the schema before its loader runs. Warn on that ambiguity rather than\n\t// failing a boot that is merely early.\n\tif (getAllMeta().length === 0) {\n\t\t// oxlint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +\n\t\t\t\t'`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +\n\t\t\t\t'have stale handler keys reported.'\n\t\t)\n\t\treturn\n\t}\n\n\tconst orphans: string[] = []\n\tfor (const [doctypeKey, handlers] of registered) {\n\t\tconst meta = getMeta(doctypeKey)\n\t\tif (!meta) {\n\t\t\torphans.push(`\"${doctypeKey}\": no doctype by that name is registered`)\n\t\t\tcontinue\n\t\t}\n\t\tif (meta.name !== doctypeKey) {\n\t\t\torphans.push(\n\t\t\t\t`\"${doctypeKey}\": matches the doctype named \"${meta.name}\" by slug, but handlers are looked up by name — key it \"${meta.name}\"`\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst actions = meta.workflow?.actions ?? {}\n\t\tfor (const actionKey of Object.keys(handlers)) {\n\t\t\tif (!(actionKey in actions)) {\n\t\t\t\torphans.push(`\"${doctypeKey}.${actionKey}\": the doctype declares no action by that key`)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (orphans.length > 0) {\n\t\tthrow new Error(\n\t\t\t`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +\n\t\t\t\t`cannot be reached and would never run:\\n ${orphans.join('\\n ')}`\n\t\t)\n\t}\n}\n\n/**\n * Refuse a doctype set whose links or `inherits` name a doctype nobody registered.\n *\n * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed\n * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response\n * with no error. On the wire that is indistinguishable from \"this record has no such relation\", and\n * a typo in a target reads as a legitimately empty link forever.\n *\n * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not\n * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.\n *\n * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns\n * because a registered handler map is evidence the host meant to be checked; here there is no such\n * evidence, so warning would fire on every host that loads doctypes after building its schema —\n * and an advisory that fires on a correct setup is worse than none. An empty registry simply\n * reports nothing, because the loop has nothing to walk.\n */\nfunction assertReferencesResolve(): void {\n\tconst broken = validateReferences()\n\tif (broken.length === 0) return\n\n\tthrow new Error(\n\t\t`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +\n\t\t\t`cannot be resolved and would silently drop the relation:\\n ` +\n\t\t\tbroken.map(e => `${e.path.join('.')}: ${e.message}`).join('\\n ')\n\t)\n}\n\n/**\n * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype\n * and both repairs. Shared so the three lookup sites report one diagnosis.\n */\nfunction unresolvableIdentityError(doctype: string): Error {\n\treturn new Error(\n\t\t`Doctype \"${doctype}\" has no identity field: it declares no field with \\`primaryKey: true\\` ` +\n\t\t\t`and no field named \\`id\\`. Declare one of the two — records cannot be fetched or acted on until then.`\n\t)\n}\n\n/**\n * Resolve the PostgreSQL FROM clause target for a doctype.\n * Uses the `tables` override map first; falls back to camelToSnake(name).\n * Schema-qualified names (e.g. \"orpin.plan\") are emitted as \"schema\".\"table\".\n * Values must be bare identifiers or schema.table pairs — not SQL fragments.\n */\n","import { wrapPlans } from 'postgraphile/utils'\n\n/**\n * Options for the Stonecrop debug plugin.\n * @public\n */\nexport interface DebugPluginOptions {\n\t/** Log a message when a plan is built for a Stonecrop field. Default: `true` */\n\tlogPlans?: boolean\n\t/** Log timing for plan construction. Default: `false` */\n\tlogTiming?: boolean\n}\n\n/**\n * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with\n * debug logging. Use it in your preset file:\n *\n * ```typescript\n * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * plugins: [createStonecropPlugin(), createDebugPlugin()],\n * }\n * ```\n *\n * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the\n * plugins array so the wrapper sees the Stonecrop fields.\n *\n * @param options - Optional logging configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createDebugPlugin = (options: DebugPluginOptions = {}): GraphileConfig.Plugin => {\n\tconst { logPlans = true, logTiming = false } = options\n\n\tconst wrapField = (typeName: string, fieldName: string) => ({\n\t\tplan: (plan: () => any) => {\n\t\t\tif (logPlans) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] Building plan for ${typeName}.${fieldName}`)\n\t\t\t}\n\n\t\t\tconst start = logTiming ? Date.now() : 0\n\t\t\tconst $result = plan()\n\n\t\t\tif (logTiming) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[@stonecrop/graphql-middleware] Plan built for ${typeName}.${fieldName} in ${Date.now() - start}ms`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn $result\n\t\t},\n\t})\n\n\treturn wrapPlans({\n\t\tQuery: {\n\t\t\tstonecropRecord: wrapField('Query', 'stonecropRecord'),\n\t\t\tstonecropRecords: wrapField('Query', 'stonecropRecords'),\n\t\t\tstonecropMeta: wrapField('Query', 'stonecropMeta'),\n\t\t\tstonecropAllMeta: wrapField('Query', 'stonecropAllMeta'),\n\t\t},\n\t\tMutation: {\n\t\t\tstonecropAction: wrapField('Mutation', 'stonecropAction'),\n\t\t},\n\t})\n}\n","import { PostGraphileAmberPreset } from 'postgraphile/presets/amber'\n\n/**\n * Controls how PostgreSQL column names are mapped to GraphQL field names in the synthesized preset.\n *\n * - `'camel'` (default): `my_column` → `myColumn`. This matches PostGraphile Amber's built-in behaviour.\n *\n * - `'pascal'`: `my_column` → `MyColumn`. Opt in via `createStonecropPreset({ fieldCasing: 'pascal' })` or\n * `grafserv.fieldCasing: 'pascal'` in `nuxt.config.ts`.\n *\n * Smart tag overrides (`@name` on column comments) are respected regardless of this setting.\n * @public\n */\nexport type FieldCasing = 'camel' | 'pascal'\n\n/**\n * Stops Amber taking `id` for Relay's global object identifier.\n *\n * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called\n * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware\n * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`\n * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not\n * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that\n * node id and every read of it then fails on a missing column.\n *\n * Both inflectors must move together. Undoing the rename alone collides with the Relay field still\n * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called\n * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier\n * to `nodeId` keeps Relay working and is the name the schema converter already skips.\n *\n * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.\n */\nconst StonecropNaturalIdPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNaturalIdPlugin',\n\tversion: '0.0.0',\n\tafter: ['PgAttributesPlugin'],\n\tinflection: {\n\t\treplace: {\n\t\t\t// Move Relay's global identifier off `id`...\n\t\t\tnodeIdFieldName() {\n\t\t\t\treturn 'nodeId'\n\t\t\t},\n\n\t\t\t// ...so the real column can keep its own name.\n\t\t\t_attributeName(previous, options, details) {\n\t\t\t\t// `previous` is optional in the inflector signature because a replacement may be the first\n\t\t\t\t// implementation. It never is here — `after: ['PgAttributesPlugin']` guarantees Amber's runs\n\t\t\t\t// first — but the raw attribute name is the correct identity fallback.\n\t\t\t\tconst name = previous?.(details) ?? details.attributeName\n\t\t\t\tif (!details.skipRowId && name === 'row_id') {\n\t\t\t\t\tconst { codec, attributeName } = details\n\t\t\t\t\tconst baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName\n\t\t\t\t\tif (typeof baseName === 'string' && baseName.toLowerCase() === 'id' && !codec.isAnonymous) {\n\t\t\t\t\t\treturn 'id'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn name\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Exposes the many side of a foreign key the database declares as owning.\n *\n * PostGraphile registers both directions of every foreign key, but Amber gives the many side no\n * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s\n * inferred behavior is `[\"resource:select\", behavior]` and nothing more. So a parent type carries\n * no field for its children, and a doctype generated from that schema can never contain a child\n * table. Every one a consumer has is hand-authored.\n *\n * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.\n * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`\n * does not: an order references a party that outlives it. The two are otherwise the same shape, so\n * no amount of reading the relation itself can separate them — and turning the many side on for\n * *every* foreign key would make each referenced table look like somebody's child.\n *\n * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw\n * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.\n *\n * Connection only, deliberately. The converter recognises a Connection type through\n * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`\n * would add a second field per relation that generation then drops on the floor.\n *\n * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the\n * global default and take precedence, so `+manyRelation:resource:connection` there is overridden\n * for every relation — verified, it changes nothing, while `-connection +list` through the same\n * option visibly rewrites the Query fields.\n */\nconst StonecropOwnedRelationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropOwnedRelationsPlugin',\n\tversion: '0.0.0',\n\tgather: {\n\t\thooks: {\n\t\t\tpgRelations_relation(_info, event) {\n\t\t\t\tconst { relation, pgConstraint } = event\n\t\t\t\t// The hook fires once per direction of each constraint; only the backwards one has a\n\t\t\t\t// many side to expose. `confdeltype` is Postgres' own code: 'c' is CASCADE.\n\t\t\t\tif (!relation.isReferencee) return\n\t\t\t\tif (pgConstraint.confdeltype !== 'c') return\n\n\t\t\t\trelation.extensions ??= {}\n\t\t\t\trelation.extensions.tags ??= {}\n\t\t\t\trelation.extensions.tags.behavior = '+manyRelation:resource:connection'\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Offers no database function as a mutation.\n *\n * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard\n * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds\n * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.\n */\nconst StonecropNoFunctionMutationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNoFunctionMutationsPlugin',\n\tversion: '0.0.0',\n\tschema: {\n\t\tentityBehavior: {\n\t\t\tpgResource: {\n\t\t\t\toverride: {\n\t\t\t\t\t// After the hook that applies smart tags, so an app's `@behavior +mutationField` cannot undo it.\n\t\t\t\t\tafter: ['PgBasicsPlugin'],\n\t\t\t\t\tcallback(behavior) {\n\t\t\t\t\t\treturn [behavior, '-mutationField']\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n}\n\nconst StonecropFieldCasingPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropFieldCasingPlugin',\n\tversion: '0.0.0',\n\tinflection: {\n\t\treplace: {\n\t\t\tattribute(previous, options, details) {\n\t\t\t\treturn this.upperCamelCase(this._attributeName(details))\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Creates a Stonecrop-flavoured PostGraphile preset.\n *\n * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's\n * recommended defaults. It turns off the mutations Amber generates, a create, update and delete for\n * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write\n * the API offers. Pass it to `extends` in your PostGraphile configuration:\n *\n * ```typescript\n * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [createStonecropPreset()],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n *\n * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable\n * `MyColumn`-style field names instead of the default `myColumn` (camelCase).\n * @public\n */\nexport const createStonecropPreset = (options?: { fieldCasing?: FieldCasing }): GraphileConfig.Preset => ({\n\textends: [PostGraphileAmberPreset],\n\tplugins: [\n\t\tStonecropNaturalIdPlugin,\n\t\tStonecropOwnedRelationsPlugin,\n\t\tStonecropNoFunctionMutationsPlugin,\n\t\t...(options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : []),\n\t],\n\t// Every write is an action, through `stonecropAction`, and Amber's create, update and delete for\n\t// each table would write past the doctype's guard. Disabled rather than set in\n\t// `schema.defaultBehavior`, which an app's own `defaultBehavior` replaces whole; `disablePlugins`\n\t// lists merge.\n\tdisablePlugins: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin'],\n})\n\n/**\n * The default Stonecrop PostGraphile preset with camelCase field names.\n *\n * Equivalent to `createStonecropPreset()` with no options. Use this when you\n * do not need to customise field casing:\n *\n * ```typescript\n * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [StonecropPreset],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n * @public\n */\nexport const StonecropPreset: GraphileConfig.Preset = createStonecropPreset()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,mBAAmB,QAA+C;CACjF,OAAO,gBAAc,MAAM,CAAC,CAAC,QAAQ,MAAuB,EAAE,SAAS,WAAW,CAAC,EAAE,QAAQ;AAC9F;;;ACtBA,IAAM,kCAA4C,IAAI,IAAI;;;;;AAM1D,IAAa,yBAAb,cAA4C,MAAM;CAGhC;CAEA;CAJjB,YAEC,MAEA,QACC;EACD,MAAM,gBAAgB,OAAO,KAAI,MAAK,KAAK,EA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AAI,CAAC;CACzE;CAKA,gBAAgB,CAAC,0BAA0B,8BAA8B;AAC1E;;;;;;;;;;;;;;;;;;AAmBA,IAAa,kBAAyC,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/fields.ts","../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/tables.ts","../src/columns.ts","../src/link-display.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["import type { DoctypeField, ValueField } from '@stonecrop/schema'\nimport { flattenFields } from '@stonecrop/schema'\n\n// Re-exported so this module stays the one place the adapter asks about a doctype's fields, while\n// the definition itself lives in `@stonecrop/schema`. It moved there because `DoctypeMeta`'s own\n// validation needs the same descent, and the copy it had written instead scanned top level only —\n// so the load gate and the read path disagreed about what a doctype declares, which is exactly\n// what keeping one definition is for.\nexport { flattenFields }\n\n/**\n * The fields that have a database column of their own — the one definition of that question.\n *\n * Two properties disqualify a field, and both are the field saying so itself: a `computed` field is\n * declared precisely to state it has no column, and a container (a table field) is a relation\n * rather than a value. Everything else names a column.\n *\n * This is deliberately **not** the same question as \"does this column belong in a record payload\".\n * An *expanding* link's foreign key has a real column that this returns, while `collectColumns`\n * omits it from the SELECT on purpose because the relation is fetched separately. Conflating the\n * two is how the read path came to drop the very column its expansion needed. Callers wanting the\n * payload projection filter this further by render mode; callers asking whether a column exists —\n * link validation, and the write path deciding what it may set — want it unfiltered.\n *\n * Extracted because the rule had grown three statements across two modules, one of them a comment\n * reading \"mirrors `collectColumns`\". A rule that has to be mirrored by hand is one edit away from\n * the read path and the validator disagreeing about what a doctype declares.\n */\nexport function columnBackedFields(fields: readonly DoctypeField[]): ValueField[] {\n\treturn flattenFields(fields).filter((f): f is ValueField => f.kind === 'field' && !f.computed)\n}\n","import { readFileSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { parseDoctype, validateDoctype } from '@stonecrop/schema'\nimport type { DoctypeMeta, ValidationError } from '@stonecrop/schema'\n\nimport { columnBackedFields, flattenFields } from '../fields'\n\nconst doctypeRegistry: Map<string, DoctypeMeta> = new Map()\n\n/**\n * Error thrown when a doctype definition fails validation\n * @public\n */\nexport class DoctypeValidationError extends Error {\n\tconstructor(\n\t\t/** File path or name where the validation error occurred */\n\t\tpublic readonly file: string,\n\t\t/** List of validation errors found */\n\t\tpublic readonly errors: ValidationError[]\n\t) {\n\t\tconst errorMessages = errors.map(e => ` ${e.path.join('.')}: ${e.message}`).join('\\n')\n\t\tsuper(`Invalid doctype definition in ${file}:\\n${errorMessages}`)\n\t\tthis.name = 'DoctypeValidationError'\n\t}\n}\n\n/**\n * Options for loading doctype definitions\n * @public\n */\nexport interface LoadDoctypesOptions {\n\t/** Continue loading other files if one fails validation */\n\tcontinueOnError?: boolean\n\t/** Callback for validation errors when continueOnError is true */\n\tonError?: (file: string, errors: ValidationError[]) => void\n}\n\n/**\n * Load doctype definitions from a directory of JSON files\n * @param dir - Directory path containing doctype JSON files\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypes(dir: string, options: LoadDoctypesOptions = {}): void {\n\tconst entries = readdirSync(dir)\n\n\tfor (const entry of entries) {\n\t\tconst fullPath = join(dir, entry)\n\t\tconst stat = statSync(fullPath)\n\n\t\tif (stat.isDirectory()) {\n\t\t\tloadDoctypes(fullPath, options)\n\t\t} else if (entry.endsWith('.json')) {\n\t\t\tloadDoctypeFile(fullPath, options)\n\t\t}\n\t}\n}\n\n/**\n * Load and validate a single doctype file\n */\nfunction loadDoctypeFile(filePath: string, options: LoadDoctypesOptions): void {\n\tconst content = readFileSync(filePath, 'utf-8')\n\tlet data: unknown\n\n\ttry {\n\t\tdata = JSON.parse(content)\n\t} catch (err) {\n\t\tconst parseError: ValidationError = {\n\t\t\tpath: [],\n\t\t\tmessage: `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`,\n\t\t}\n\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, [parseError])\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, [parseError])\n\t}\n\n\tconst result = validateDoctype(data)\n\n\tif (!result.success) {\n\t\tif (options.continueOnError) {\n\t\t\toptions.onError?.(filePath, result.errors)\n\t\t\treturn\n\t\t}\n\t\tthrow new DoctypeValidationError(filePath, result.errors)\n\t}\n\n\tconst doctype = parseDoctype(data)\n\tdoctypeRegistry.set(doctype.name, doctype)\n}\n\n/**\n * Load doctypes from an object (for programmatic use)\n * @param doctypes - Object mapping doctype names to doctype definitions\n * @param options - Options for loading doctypes (continueOnError, onError callback)\n * @public\n */\nexport function loadDoctypesFromObject(doctypes: Record<string, unknown>, options: LoadDoctypesOptions = {}): void {\n\tfor (const [name, data] of Object.entries(doctypes)) {\n\t\tconst withName = { ...(typeof data === 'object' && data !== null ? data : {}), name }\n\t\tconst result = validateDoctype(withName)\n\n\t\tif (!result.success) {\n\t\t\tif (options.continueOnError) {\n\t\t\t\toptions.onError?.(name, result.errors)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthrow new DoctypeValidationError(name, result.errors)\n\t\t}\n\n\t\tconst doctype = parseDoctype(withName)\n\t\tdoctypeRegistry.set(doctype.name, doctype)\n\t}\n}\n\n/**\n * Get a doctype by name\n * @param name - Name of the doctype to retrieve\n * @public\n */\nexport function getMeta(name: string): DoctypeMeta | undefined {\n\tconst direct = doctypeRegistry.get(name)\n\tif (direct) return direct\n\t// Fallback: find by slug (links reference doctypes by slug, not name)\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\tif (doctype.slug === name) return doctype\n\t}\n\treturn undefined\n}\n\n/**\n * Get all loaded doctypes\n * @public\n */\nexport function getAllMeta(): DoctypeMeta[] {\n\treturn Array.from(doctypeRegistry.values())\n}\n\n/**\n * Check if a doctype is registered\n * @param name - Name of the doctype to check\n * @public\n */\nexport function hasMeta(name: string): boolean {\n\treturn doctypeRegistry.has(name)\n}\n\n/**\n * Clear all registered doctypes\n * @public\n */\nexport function clearRegistry(): void {\n\tdoctypeRegistry.clear()\n}\n\n/**\n * Validate doctype references — link targets, `inherits`, and each link's binding — against what\n * is loaded.\n *\n * Resolution goes through `getMeta`, never through the registry Map directly. The Map is keyed by\n * doctype **name** while a link target is a **slug** (`DoctypeMeta.links[].target` is documented as\n * one, and every doctype in this repo writes one), so a raw `.has()` reports a broken reference for\n * every correct link — measured at 12 of 12 across the two in-repo hosts before this was fixed.\n * `getMeta` is also what the plugin resolves a link with at fetch time, so this asks the same\n * question the runtime asks.\n *\n * `inherits` is checked the same way even though nothing resolves it at runtime (both resolvers\n * only echo it onto the wire) — one rule is cheaper than two, and it cannot be wrong in the\n * permissive direction.\n *\n * The **binding** checks are the same defect class as an unresolvable target, one step further in:\n * a link whose target resolves can still name no way to reach the rows, and the reader's answer for\n * that is `continue` or a `null` — indistinguishable on the wire from a relation that is genuinely\n * empty. Both halves of a declaration are `.optional()` in the schema because which one is required\n * depends on cardinality, which Zod cannot express here; this is where that dependency is enforced.\n *\n * Only what the runtime actually consults is required. A `backlink` naming a column the target\n * table does not have already fails loudly — Postgres rejects the SELECT — so it is left alone;\n * the check exists for the silent cases, not to restate the database's own errors.\n *\n * Returns rather than throws so the caller decides; `assertReferencesResolve` in the plugin is that\n * caller. Kept out of the package's public exports: it reads a module-level registry, so it is only\n * meaningful after this module's own loaders have run.\n *\n * @internal\n */\nexport function validateReferences(): ValidationError[] {\n\tconst errors: ValidationError[] = []\n\n\tfor (const doctype of doctypeRegistry.values()) {\n\t\t// Check inherits reference\n\t\tif (doctype.inherits && getMeta(doctype.inherits) === undefined) {\n\t\t\terrors.push({\n\t\t\t\tpath: [doctype.name, 'inherits'],\n\t\t\t\tmessage: `References unknown doctype: ${doctype.inherits}`,\n\t\t\t})\n\t\t}\n\n\t\tconst fields = flattenFields(doctype.fields)\n\n\t\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && getMeta(target) === undefined) {\n\t\t\t\terrors.push({\n\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'doctype'],\n\t\t\t\t\tmessage: `Link references unknown doctype: ${target}`,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Check link-declaration targets (component-primary links live in the `links` map)\n\t\tif (doctype.links) {\n\t\t\tconst declared = new Set(fields.map(f => f.fieldname))\n\t\t\t// A foreign key is read from a column, so a link can only bind to a field that has one.\n\t\t\t// The rule itself lives in one place — see `columnBackedFields` — because the read path,\n\t\t\t// the write path and this check all have to answer it the same way.\n\t\t\tconst columnBacked = new Set(columnBackedFields(doctype.fields).map(f => f.fieldname))\n\n\t\t\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (getMeta(link.target) === undefined) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'target'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${link.target}`,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// A custom fetch strategy hands the whole read to its handler, which is given the\n\t\t\t\t// row and the declaration and finds the target however it likes. The runtime returns\n\t\t\t\t// before consulting either binding below, so requiring one would refuse a link that\n\t\t\t\t// works.\n\t\t\t\tif (link.fetch?.method === 'custom') continue\n\n\t\t\t\t// The two cardinalities bind through different halves of the declaration, so the\n\t\t\t\t// check has to split the same way the reader does.\n\t\t\t\tif (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') {\n\t\t\t\t\t// Many-side: the target rows are found by a column on the *target* table, so\n\t\t\t\t\t// this doctype needs no field of its own — and the in-repo hosts disagree on\n\t\t\t\t\t// whether one exists, which is why only `backlink` can be required here.\n\t\t\t\t\tif (!link.backlink) {\n\t\t\t\t\t\terrors.push({\n\t\t\t\t\t\t\tpath: [doctype.name, 'links', key, 'backlink'],\n\t\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\t`Link \"${key}\" is ${link.cardinality} but names no \\`backlink\\`, so the runtime cannot ` +\n\t\t\t\t\t\t\t\t`find the target rows and drops the link with no error. Name the field on \"${link.target}\" ` +\n\t\t\t\t\t\t\t\t`that points back to this doctype.`,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// One-side: the foreign key is a column on *this* table, read as\n\t\t\t\t// `link.fieldname ?? key`. A name matching no declared field is not selected, so the\n\t\t\t\t// link resolves to null forever and reads as \"this record has no such relation\".\n\t\t\t\tconst fieldname = link.fieldname ?? key\n\t\t\t\tif (!columnBacked.has(fieldname)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\t// Point at whichever half actually carries the binding: the `fieldname`\n\t\t\t\t\t\t// property when it is set, otherwise the key itself. Naming `target` here\n\t\t\t\t\t\t// would send the reader to the one part that resolved correctly.\n\t\t\t\t\t\tpath: link.fieldname ? [doctype.name, 'links', key, 'fieldname'] : [doctype.name, 'links', key],\n\t\t\t\t\t\t// Two different repairs, so two different diagnoses: a name nothing declares\n\t\t\t\t\t\t// is a typo, while a name that resolves to a column-less field is a binding\n\t\t\t\t\t\t// pointed at the wrong one of several real fields.\n\t\t\t\t\t\tmessage: declared.has(fieldname)\n\t\t\t\t\t\t\t? `Link \"${key}\" binds to field \"${fieldname}\", which has no database column of its own — ` +\n\t\t\t\t\t\t\t\t`it is computed, or a container rather than a value — so there is no foreign key to read ` +\n\t\t\t\t\t\t\t\t`and the record read fails on the missing column. Bind the link to the field holding the ` +\n\t\t\t\t\t\t\t\t`foreign key.`\n\t\t\t\t\t\t\t: `Link \"${key}\" binds to field \"${fieldname}\", which this doctype does not declare, so it ` +\n\t\t\t\t\t\t\t\t`resolves to null with no error. Declare that field, or set \\`fieldname\\` to the field ` +\n\t\t\t\t\t\t\t\t`holding the foreign key. (A link's key is its fieldname unless \\`fieldname\\` overrides it.)`,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors\n}\n","import type { PgClient } from '@dataplan/pg'\nimport type { LinkDeclaration } from '@stonecrop/schema'\n\n/**\n * Handler for a custom fetch strategy on a link declaration.\n * Called during `stonecropRecord` resolution when `link.fetch.method === 'custom'`.\n *\n * @param pgClient - Active database client for the current request\n * @param parentRecord - Resolved parent record (scalar fields already populated)\n * @param link - The link declaration, giving access to cardinality and other metadata\n * @returns A single linked record or an array depending on `link.cardinality`\n * @public\n */\nexport type FetchHandler = (\n\tpgClient: PgClient,\n\tparentRecord: Record<string, unknown>,\n\tlink: LinkDeclaration\n) => Promise<Record<string, unknown> | Record<string, unknown>[]>\n\nconst registry = new Map<string, FetchHandler>()\n\n/**\n * Register a custom fetch handler by name.\n * The name must match the `handler` field on a `CustomFetch` strategy declaration.\n * @public\n */\nexport function registerFetchHandler(name: string, handler: FetchHandler): void {\n\tregistry.set(name, handler)\n}\n\n/**\n * Retrieve a registered fetch handler by name.\n * Returns `undefined` if no handler has been registered under that name.\n * @public\n */\nexport function getFetchHandler(name: string): FetchHandler | undefined {\n\treturn registry.get(name)\n}\n\n/**\n * Remove all registered fetch handlers. Primarily for test isolation.\n * @public\n */\nexport function clearFetchHandlers(): void {\n\tregistry.clear()\n}\n","import { isActionAllowedInState } from '@stonecrop/schema'\n\n/**\n * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.\n * The same guard runs whether the record lives in Postgres, a mock executor, or an\n * in-memory Map — only these closures change per backend.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/**\n\t * Read the record's current workflow state — the value of its `status` field.\n\t *\n\t * Three answers, and the difference between the last two matters: a string is the record's\n\t * current state, `undefined` means the record exists but carries no workflow state, and `null`\n\t * means **there is no such record**.\n\t *\n\t * Collapsing those two into `undefined` is what let an action against a missing record report\n\t * success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and\n\t * the write then found nothing to write. Backends must return `null` when the lookup misses.\n\t */\n\treadState: () => Promise<string | null | undefined>\n\t/** Persist the record's new workflow state, written verbatim. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Persist a record's field data for a self-transition, returning the full record as it now\n\t * stands, which states its identity (the only place a created record's key is known).\n\t *\n\t * **This is an upsert, and it is the create path.** Saving a record is one request whether or\n\t * not the row is there yet, so there is no create action and no create mutation — `exists` says\n\t * which case you are in, and the second argument exists only because the dispatcher already\n\t * knows: it read the record's state to run the guard. When `exists` is false, mint or derive the\n\t * identity here and return the created record; identity is the backend's business, not the\n\t * dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that\n\t * value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.\n\t *\n\t * Never return an empty object for a creation: the dispatcher treats that as a backend that\n\t * only knows how to patch, and fails loudly rather than reporting a save that stored nothing.\n\t *\n\t * Optional. A backend with no data-write path omits it, which is how it declines both saving\n\t * and creating; a self-transition is then rejected loudly rather than silently dropped — unless\n\t * `runEffect` is supplied, in which case the handler is the persistence path.\n\t */\n\twriteData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>\n\t/**\n\t * Run the adapter's side effect for this action, after the guard has passed and before any\n\t * state is written. This is the seam a **database author** wires — see\n\t * `StonecropPluginOptions.actionHandlers` for the Postgres adapter's registration surface.\n\t *\n\t * It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at\n\t * all: without one, such an action has nothing to apply and fails loudly.\n\t *\n\t * Throwing rejects the action, so the dispatcher writes neither data nor state. It does **not**\n\t * undo writes the handler already made: this guard is storage-agnostic and owns no transaction,\n\t * and the Postgres adapter in particular dispatches outside one. A handler whose own statements\n\t * must be all-or-nothing has to wrap them itself.\n\t *\n\t * What it returns becomes the result's `data`, verbatim; returning `undefined` leaves the\n\t * doctype's own outcome to decide `data`. The client stores the adapter's read of the record,\n\t * never this.\n\t *\n\t * @param currentState - The state the guard read, or `undefined` when nothing required reading it\n\t * @returns The updated record, or `undefined` to leave the result payload to the state outcome\n\t */\n\trunEffect?: (currentState: string | undefined) => Promise<unknown>\n}\n\n/**\n * Apply a workflow action on the server, enforcing `allowedStates`.\n *\n * The server owns the transition: it reads the record's authoritative current state,\n * rejects the action when `isActionAllowedInState` denies it, then applies the outcome.\n * Storage access is injected via `io` so this one guard serves every backend and can never\n * disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.\n *\n * **The doctype decides whether an action may run and what state results; the adapter decides\n * what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the\n * doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever\n * owns the database. Neither names the other: an action never carries a handler name, and a\n * handler never overrides the guard.\n *\n * There are four action shapes this distinguishes:\n *\n * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\n *\n * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current\n * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.\n * When the target record does not exist the same write creates it — saving a record is one\n * request whether or not the row is there yet, so there is no separate create action, no create\n * mutation, and no second write path for it.\n *\n * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole\n * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.\n *\n * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine\n * authoring mistake or a command whose handler was never wired. It fails loudly before touching\n * the backend rather than reporting a false success.\n *\n * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`\n * @param io - Backend read/write closures, plus the optional adapter-owned effect\n * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)\n * @returns Action result envelope — the freshest record the backend produced, or the resulting state\n * @public\n */\nexport async function applyGuardedTransition(\n\tactionDef: { label?: string; allowedStates?: string[]; nextState?: string; selfTransition?: boolean },\n\tio: GuardedTransitionIO,\n\tdata?: Record<string, unknown>\n): Promise<{ success: boolean; data: unknown; error: string | null }> {\n\tconst label = actionDef.label ?? 'unknown'\n\tconst isSelfTransition = actionDef.selfTransition === true\n\tconst hasStateOutcome = isSelfTransition || actionDef.nextState != null\n\n\t// Nothing to apply and no effect registered — fail loudly WITHOUT touching the backend.\n\t// This is the honest report for both causes: an action authored with no outcome, and a\n\t// command whose server handler the adapter never registered.\n\tif (!hasStateOutcome && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" has no workflow transition and no server-side effect is wired — nothing was executed. Give it a nextState or selfTransition in the doctype, or register a server-side handler for it on the adapter.`,\n\t\t}\n\t}\n\n\t// A self-transition exists to persist data; with no way at all to do that — no data write, no\n\t// create, no effect — reject before running anything rather than half-applying.\n\tif (isSelfTransition && !io.writeData && !io.runEffect) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${label}\" persists record data in place, which this backend does not support.`,\n\t\t}\n\t}\n\n\t// Read the authoritative state only when something actually consumes it: the guard, or a\n\t// state outcome that the caller's readState is paired with. A handler-only command on a\n\t// doctype with no `status` column must not be forced through a read it never uses.\n\tconst isGuarded = (actionDef.allowedStates?.length ?? 0) > 0\n\tlet currentState: string | undefined\n\tif (isGuarded || hasStateOutcome) {\n\t\tconst state = await io.readState()\n\t\t// A missing record is reported, never guarded around. Reaching the guard with a state of\n\t\t// `''` produced two wrong answers depending only on whether the action declared\n\t\t// `allowedStates`: a misleading \"not allowed from state: (unknown)\" when it did, and a\n\t\t// silent `{ success: true }` writing nothing when it did not.\n\t\tif (state === null) {\n\t\t\t// A self-transition against a record that is not there is a create — the same write,\n\t\t\t// against a row that does not exist yet. The guard is deliberately skipped:\n\t\t\t// `allowedStates` constrains movement between states, and a record being created is not\n\t\t\t// in one; its initial state is the backend's to set.\n\t\t\t//\n\t\t\t// A registered effect does NOT run here. An effect is written against an existing row,\n\t\t\t// and firing it against a just-created one is a different contract than the one it was\n\t\t\t// registered under; making creation observable to effects is deferred rather than\n\t\t\t// guessed at.\n\t\t\tif (isSelfTransition && io.writeData) {\n\t\t\t\tconst created = await io.writeData(data ?? {}, false)\n\t\t\t\t// A backend that only knows how to patch returns nothing here, having matched no\n\t\t\t\t// row. Reporting that as success is the exact bug the `null` answer above exists to\n\t\t\t\t// kill, so it must not come back through the create path.\n\t\t\t\tif (!created || Object.keys(created).length === 0) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\terror: `Action \"${label}\" targets a record that does not exist, and the backend did not create it.`,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { success: true, data: created, error: null }\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" targets a record that does not exist — nothing was executed.`,\n\t\t\t}\n\t\t}\n\t\tcurrentState = state ?? ''\n\t}\n\n\tif (!isActionAllowedInState(actionDef, currentState ?? '')) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action not allowed from state: ${currentState || '(unknown)'}`,\n\t\t}\n\t}\n\n\t// The effect runs after the guard and before any write, so a handler that rejects cannot\n\t// leave the record in the target state. Its throw is attributed to the action by name —\n\t// the adapter's handler is code the doctype author cannot see, so an anonymous failure\n\t// would be undebuggable from either side.\n\tlet effectResult: unknown\n\tif (io.runEffect) {\n\t\ttry {\n\t\t\teffectResult = await io.runEffect(currentState)\n\t\t} catch (err) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${label}\" failed: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t}\n\t\t}\n\t}\n\n\t// Self-transition: mutate record data in place, keep the current state. The full updated\n\t// record is returned so a created record's identity is known. When the backend has no\n\t// data-write path the effect above already did the persisting (guarded at the top).\n\tif (isSelfTransition) {\n\t\tconst record = io.writeData ? await io.writeData(data ?? {}, true) : effectResult\n\t\treturn { success: true, data: record ?? null, error: null }\n\t}\n\n\t// NON-ATOMIC: the current state is read above and nextState written here as two\n\t// separate statements — and a registered effect runs between them. Two concurrent\n\t// transitions on the same record can both pass the guard before either writes, so both\n\t// \"succeed\" even when the workflow intended them to be mutually exclusive. Closing this\n\t// requires guarding and writing in one statement — an atomic\n\t// `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)` — and reporting\n\t// \"no rows updated\" as a rejected transition. Deferred for now.\n\tif (actionDef.nextState == null) {\n\t\t// A stateless command: the effect (guaranteed present by the top guard) is the whole\n\t\t// outcome. It must not move the record — that is the doctype's call, not the handler's.\n\t\treturn { success: true, data: effectResult ?? null, error: null }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\t// The freshest thing the backend produced wins: a handler that returned a record describes\n\t// the row better than the state alone, which is all a bare transition knows.\n\treturn {\n\t\tsuccess: true,\n\t\tdata: effectResult ?? { state: actionDef.nextState },\n\t\terror: null,\n\t}\n}\n","import { pascalToSnake } from '@stonecrop/schema'\n\n/** A table a doctype reads from, as named before quoting. `schema` is absent for an unqualified name. */\nexport interface TableRef {\n\tschema?: string\n\tname: string\n}\n\n/**\n * The table a doctype reads from: the `tables` override when the adapter supplies one, otherwise the\n * doctype name snake-cased.\n *\n * The one definition of that mapping. It lives in its own module rather than beside either caller\n * because the plugin imports the link-display enrichment, so the enrichment cannot import back —\n * and the copy it made instead was byte-identical, which is the state a mapping is in right before\n * one side learns about schema-qualified names and the other does not.\n *\n * A dotted override is read as `schema.table`, so a table in a non-default Postgres schema keeps\n * its schema instead of becoming one name containing a dot.\n */\nexport function resolveTable(name: string, tables?: Record<string, string>): TableRef {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn { schema: target.slice(0, dotIndex), name: target.slice(dotIndex + 1) }\n\t}\n\treturn { name: target }\n}\n\n/** The quoted SQL table a doctype reads from (see `resolveTable`). */\nexport function resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst table = resolveTable(name, tables)\n\treturn table.schema === undefined ? `\"${table.name}\"` : `\"${table.schema}\".\"${table.name}\"`\n}\n","import { LIST_TYPES, TYPES } from '@dataplan/pg'\nimport type { PgCodec, PgCodecAttribute, PgExecutor } from '@dataplan/pg'\nimport { sql } from 'postgraphile/pg-sql2'\nimport type { SQL } from 'postgraphile/pg-sql2'\nimport { Temporal } from 'temporal-polyfill'\n\nimport { resolveTable, resolveTableName } from './tables'\n\n/** A column to read, and the key its value comes back under. */\nexport interface ColumnSelection {\n\tcolumn: string\n\talias: string\n}\n\n/** One doctype's table, with a select list whose values read as PostGraphile reads them. */\nexport interface ColumnSelect {\n\t/** The quoted table. */\n\ttable: string\n\t/** Each column cast to text the way PostGraphile casts it, under its alias. */\n\tlist: string\n\t/** Decodes every selected value in place with the codec PostGraphile decodes it with. */\n\tdecodeRows(rows: readonly Record<string, unknown>[]): void\n}\n\n/** Builds the select list for a doctype's columns, and the SQL that binds a value to one. */\nexport interface ColumnReader {\n\tselect(doctype: string, selections: readonly ColumnSelection[]): ColumnSelect\n\t/** `placeholder` as the value for `column`, cast where the column needs its value converted. */\n\tbind(doctype: string, column: string, placeholder: string): string\n\t/** Whether a write may set `column`: not one the database fills itself, which PostGraphile marks as neither insertable nor updatable. */\n\twritable(doctype: string, column: string): boolean\n}\n\n/** A domain's underlying type, through any domains stacked on it. */\nconst baseCodec = (codec: PgCodec): PgCodec => (codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec)\n\n/** How a column whose values carry no zone is converted into the moments they name. */\ninterface MomentConversion {\n\t/** The type Postgres converts it to, through the database's zone. */\n\ttype: 'timestamptz' | 'timestamptz[]'\n\tcastSql: SQL\n\t/** Reads the converted value as PostGraphile reads that type. */\n\tcodec: PgCodec\n}\n\n/**\n * The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which\n * names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast\n * Postgres itself makes through the database's zone, so a value leaves as a moment and a moment\n * comes back to the same reading. Every other column needs none.\n *\n * Not PostGraphile's own text for it: that carries no zone, so a browser reads it in its own zone\n * and sends back UTC, and every save moved the stored time by the user's offset.\n */\nconst momentConversion = (codec: PgCodec): MomentConversion | undefined => {\n\tif (baseCodec(codec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz', castSql: sql`::timestamptz`, codec: TYPES.timestamptz }\n\t}\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.timestamp) {\n\t\treturn { type: 'timestamptz[]', castSql: sql`::timestamptz[]`, codec: LIST_TYPES.timestamptz }\n\t}\n\treturn undefined\n}\n\nconst INTERVAL_PARTS = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] as const\n\n/**\n * An interval, as PostGraphile decodes it, written as an ISO 8601 duration (`P1DT2H30M`): the value\n * a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Not PostGraphile's object,\n * which every other backend would have to imitate. Postgres writes an ISO 8601 duration back natively.\n *\n * Postgres signs each part apart, so it can hold \"a day less an hour\", which no ISO 8601 duration can.\n * Such an interval throws rather than being read as some other length.\n */\nconst isoDuration = (interval: unknown, describe: () => string): string => {\n\tconst part = (name: (typeof INTERVAL_PARTS)[number]) => {\n\t\tconst value: unknown = interval instanceof Object ? Reflect.get(interval, name) : undefined\n\t\treturn typeof value === 'number' ? value : 0\n\t}\n\tconst parts = INTERVAL_PARTS.map(part)\n\tif (parts.some(value => value > 0) && parts.some(value => value < 0)) {\n\t\tthrow new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`)\n\t}\n\tconst microseconds = Math.round(part('seconds') * 1e6)\n\treturn Temporal.Duration.from({\n\t\tyears: part('years'),\n\t\tmonths: part('months'),\n\t\tdays: part('days'),\n\t\thours: part('hours'),\n\t\tminutes: part('minutes'),\n\t\tseconds: Math.trunc(microseconds / 1e6),\n\t\tmilliseconds: Math.trunc((microseconds % 1e6) / 1e3),\n\t\tmicroseconds: microseconds % 1e3,\n\t}).toString()\n}\n\nconst readIntervalList = (intervals: unknown, describe: () => string): unknown =>\n\tArray.isArray(intervals)\n\t\t? intervals.map((interval: unknown) => (interval === null ? null : isoDuration(interval, describe)))\n\t\t: intervals\n\n/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */\nconst intervalShape = (codec: PgCodec): 'one' | 'list' | undefined => {\n\tif (baseCodec(codec) === TYPES.interval) return 'one'\n\tif (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.interval) return 'list'\n\treturn undefined\n}\n\n/**\n * Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each\n * value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is\n * `2026-01-01`. Two exceptions: a `timestamp`, or a list of them, served as the moment each names in\n * the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`), and an\n * `interval`, or a list of them, served as an ISO 8601 duration (see `isoDuration`).\n *\n * Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,\n * which names another day or hour outside UTC, and a save writes that shifted value back. Not a\n * process-wide `setTypeParser` either, which changes every other `pg` query in the host.\n */\nexport function createColumnReader(\n\tcodecs: Readonly<Record<string, PgCodec>>,\n\texecutor: PgExecutor,\n\ttables?: Record<string, string>\n): ColumnReader {\n\tconst tableCodecsByName = new Map<string, PgCodec[]>()\n\tfor (const codec of Object.values(codecs)) {\n\t\tconst pg = codec.extensions?.pg\n\t\tif (!codec.attributes || !codec.extensions?.isTableLike || !pg || codec.executor !== executor) continue\n\t\ttableCodecsByName.set(pg.name, [...(tableCodecsByName.get(pg.name) ?? []), codec])\n\t}\n\n\tconst findTableCodec = (doctype: string): PgCodec => {\n\t\tconst table = resolveTable(doctype, tables)\n\t\tconst matches = (tableCodecsByName.get(table.name) ?? []).filter(\n\t\t\tcodec => table.schema === undefined || codec.extensions?.pg?.schemaName === table.schema\n\t\t)\n\t\tif (matches.length === 1) return matches[0]\n\t\tconst quoted = resolveTableName(doctype, tables)\n\t\tif (matches.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" reads ${quoted}, which PostGraphile has not introspected, so its columns ` +\n\t\t\t\t\t`cannot be read the way PostGraphile reads them. Add the table's schema to the pgService, ` +\n\t\t\t\t\t`or map the doctype in \\`tables\\` to a table PostGraphile knows.`\n\t\t\t)\n\t\t}\n\t\tconst schemas = matches.map(codec => codec.extensions?.pg?.schemaName).join(', ')\n\t\tthrow new Error(\n\t\t\t`Doctype \"${doctype}\" reads ${quoted}, a name PostGraphile knows in more than one schema ` +\n\t\t\t\t`(${schemas}). Map the doctype in \\`tables\\` to \"schema.table\".`\n\t\t)\n\t}\n\n\tconst findAttribute = (doctype: string, tableCodec: PgCodec, column: string): PgCodecAttribute => {\n\t\tconst attribute = tableCodec.attributes?.[column]\n\t\tif (!attribute) {\n\t\t\tthrow new Error(\n\t\t\t\t`Doctype \"${doctype}\" declares a field for column \"${column}\", which ${resolveTableName(doctype, tables)} does not have.`\n\t\t\t)\n\t\t}\n\t\treturn attribute\n\t}\n\n\treturn {\n\t\tselect(doctype, selections) {\n\t\t\tconst tableCodec = findTableCodec(doctype)\n\t\t\tconst table = resolveTableName(doctype, tables)\n\t\t\t// Keyed by alias, so a column selected twice under one key is decoded once, as `pg` keeps one.\n\t\t\tconst decoders = new Map<string, (value: string) => unknown>()\n\t\t\tconst list = selections\n\t\t\t\t.map(({ column, alias }) => {\n\t\t\t\t\tconst columnCodec = findAttribute(doctype, tableCodec, column).codec\n\t\t\t\t\tconst conversion = momentConversion(columnCodec)\n\t\t\t\t\tconst readCodec = conversion?.codec ?? columnCodec\n\t\t\t\t\tconst columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column)\n\t\t\t\t\tconst cast = readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`\n\t\t\t\t\tconst compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`)\n\t\t\t\t\t// This list is spliced into SQL whose placeholders the caller numbers, so a cast carrying\n\t\t\t\t\t// its own `$1` would silently bind the caller's first value.\n\t\t\t\t\tif (compiled.values.length > 0) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The codec for ${table}.\"${column}\" casts with a bound value, which this adapter cannot select.`\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tconst shape = intervalShape(columnCodec)\n\t\t\t\t\tconst describe = (text: string) => () => `\"${alias}\" from ${table} (${text})`\n\t\t\t\t\tdecoders.set(\n\t\t\t\t\t\talias,\n\t\t\t\t\t\tshape === 'one'\n\t\t\t\t\t\t\t? text => isoDuration(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t: shape === 'list'\n\t\t\t\t\t\t\t\t? text => readIntervalList(readCodec.fromPg(text), describe(text))\n\t\t\t\t\t\t\t\t: readCodec.fromPg\n\t\t\t\t\t)\n\t\t\t\t\treturn compiled.text\n\t\t\t\t})\n\t\t\t\t.join(', ')\n\n\t\t\treturn {\n\t\t\t\ttable,\n\t\t\t\tlist,\n\t\t\t\tdecodeRows(rows) {\n\t\t\t\t\tfor (const row of rows) {\n\t\t\t\t\t\tfor (const [alias, fromPg] of decoders) {\n\t\t\t\t\t\t\tconst value = row[alias]\n\t\t\t\t\t\t\tif (value === null) continue\n\t\t\t\t\t\t\t// The list casts every column to text, so anything else is a row this select did not\n\t\t\t\t\t\t\t// produce, or one decoded already.\n\t\t\t\t\t\t\tif (typeof value !== 'string') {\n\t\t\t\t\t\t\t\tthrow new Error(`\"${alias}\" from ${table} is ${typeof value}, not the text its select returns.`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow[alias] = fromPg(value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\n\t\tbind(doctype, column, placeholder) {\n\t\t\tconst conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec)\n\t\t\treturn conversion ? `${placeholder}::${conversion.type}` : placeholder\n\t\t},\n\n\t\twritable(doctype, column) {\n\t\t\tconst { extensions } = findAttribute(doctype, findTableCodec(doctype), column)\n\t\t\treturn extensions?.isInsertable !== false || extensions?.isUpdatable !== false\n\t\t},\n\t}\n}\n","import type { DoctypeMeta } from '@stonecrop/schema'\nimport { camelToSnake, flattenFields, getDisplayField, getRecordIdField } from '@stonecrop/schema'\nimport type { PgClient } from '@dataplan/pg'\n\nimport type { ColumnReader } from './columns'\nimport { getMeta } from './registry/doctypes'\n\ntype SqlQueryFn = (\n\tpgClient: PgClient,\n\tquery: { text: string; values?: unknown[] }\n) => Promise<{ rows: readonly Record<string, unknown>[] }>\n\ninterface LinkDisplaySpec {\n\tfieldname: string\n\tdisplayField: string\n\ttargetPkFieldname: string\n\ttargetDoctype: string\n}\n\n/**\n * Normalize a scalar SQL cell value to a non-empty string, or nothing.\n *\n * One rule for the three reads that all need it — the FK a lookup keys on, the target's own key\n * in the result, and the display text stamped into the payload. Rejecting objects is what each\n * of those wants: an object FK is a link that was already expanded, and an object display column\n * is the `[object Object]` a bare `String()` would otherwise write into the payload as though it\n * were the record's name. Falling back to the raw id is visibly unhelpful; that is not.\n */\nfunction scalarText(value: unknown): string | undefined {\n\tif (value == null || typeof value === 'object') return undefined\n\tif (typeof value === 'string') return value === '' ? undefined : value\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n\t\treturn String(value)\n\t}\n\treturn undefined\n}\n\nfunction collectLinkDisplaySpecs(meta: DoctypeMeta): LinkDisplaySpec[] {\n\tconst specs: LinkDisplaySpec[] = []\n\n\tfor (const field of flattenFields(meta.fields)) {\n\t\tif (field.kind !== 'field' || !field.doctype) continue\n\n\t\tconst targetMeta = getMeta(field.doctype)\n\t\tif (!targetMeta) continue\n\n\t\t// `getDisplayField` rather than a lookup written here: it is the same call `DoctypeMeta`\n\t\t// makes at the load gate, so a nomination that parsed is one this can build a SELECT from.\n\t\t// A hand-rolled scan here admitted `computed` fields, whose column does not exist.\n\t\tconst displayField = getDisplayField(targetMeta.fields, targetMeta.displayField)\n\t\tif (!displayField) continue\n\n\t\tspecs.push({\n\t\t\tfieldname: field.fieldname,\n\t\t\tdisplayField: displayField.fieldname,\n\t\t\ttargetPkFieldname: getRecordIdField(targetMeta.fields),\n\t\t\ttargetDoctype: targetMeta.name,\n\t\t})\n\t}\n\n\treturn specs\n}\n\n/**\n * Replace inline link FK scalars with `{ id, displayText }` when the target doctype declares a\n * `displayField`. Expanded relations (object values) are skipped.\n *\n * Takes every row at once and issues one lookup per FK field, not per row. Callers holding a batch\n * must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the\n * loader exists to prevent, and does so invisibly, since the result is identical either way.\n */\nexport async function enrichLinkDisplayFields(\n\tpgClient: PgClient,\n\tmeta: DoctypeMeta,\n\trows: Record<string, unknown>[],\n\tcolumns: ColumnReader,\n\tdebugSql: SqlQueryFn\n): Promise<void> {\n\tconst specs = collectLinkDisplaySpecs(meta)\n\tif (specs.length === 0 || rows.length === 0) return\n\n\tawait Promise.all(\n\t\tspecs.map(async spec => {\n\t\t\tconst ids = new Set<string>()\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = scalarText(row[spec.fieldname])\n\t\t\t\tif (id !== undefined) ids.add(id)\n\t\t\t}\n\t\t\tif (ids.size === 0) return\n\n\t\t\tconst pkColumn = camelToSnake(spec.targetPkFieldname)\n\t\t\tconst select = columns.select(spec.targetDoctype, [\n\t\t\t\t{ column: pkColumn, alias: spec.targetPkFieldname },\n\t\t\t\t{ column: camelToSnake(spec.displayField), alias: spec.displayField },\n\t\t\t])\n\n\t\t\tconst { rows: displayRows } = await debugSql(pgClient, {\n\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\tvalues: [Array.from(ids)],\n\t\t\t})\n\t\t\tselect.decodeRows(displayRows)\n\n\t\t\tconst displayById = new Map<string, string>()\n\t\t\tfor (const displayRow of displayRows) {\n\t\t\t\tconst key = scalarText(displayRow[spec.targetPkFieldname])\n\t\t\t\tconst text = scalarText(displayRow[spec.displayField])\n\t\t\t\tif (key === undefined || text === undefined) continue\n\t\t\t\tdisplayById.set(key, text)\n\t\t\t}\n\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst rawId = row[spec.fieldname]\n\t\t\t\tconst idKey = scalarText(rawId)\n\t\t\t\tif (idKey === undefined) continue\n\t\t\t\tconst displayText = displayById.get(idKey)\n\t\t\t\tif (displayText === undefined) continue\n\t\t\t\trow[spec.fieldname] = { id: rawId, displayText }\n\t\t\t}\n\t\t})\n\t)\n}\n","import { gql } from 'postgraphile/utils'\n\n/**\n * GraphQL type definitions for Stonecrop's middleware API.\n * Includes stonecropMeta, stonecropRecord, stonecropRecords, stonecropAction, and related types.\n * @public\n */\nexport const typeDefs = gql`\n\ttype StonecropFieldMeta {\n\t\tkind: String!\n\t\tfieldname: String!\n\t\tcomponent: String\n\t\tprimaryKey: Boolean\n\t\tcomputed: Boolean\n\t\tlanguage: String\n\t\tdoctype: String\n\t\tlabel: String\n\t\twidth: String\n\t\theight: String\n\t\talign: String\n\t\tedit: Boolean\n\t\tmask: String\n\t\tformat: String\n\t\tmode: String\n\t\toptions: JSON\n\t\tparts: JSON\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\tvalidation: JSON\n\t\tcardinality: String\n\t\tsource: String\n\t\tconfig: JSON\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tnextState: String\n\t\tstateless: Boolean\n\t\tselfTransition: Boolean\n\t\tclientHandler: String\n\t}\n\n\ttype StonecropWorkflowMeta {\n\t\tstates: [String!]\n\t\tactions: [StonecropWorkflowAction!]\n\t}\n\n\ttype StonecropDoctypeMeta {\n\t\tname: String!\n\t\tslug: String\n\t\tdisplayField: String\n\t\tfields: [StonecropFieldMeta!]!\n\t\tworkflow: StonecropWorkflowMeta\n\t\tinherits: String\n\t}\n\n\ttype StonecropRecordResult {\n\t\tdata: JSON\n\t\tdoctype: String!\n\t\tunknownLinks: [String!]\n\t\t\"\"\"\n\t\tFields whose linked rows were cut short by a row cap, so data holds a prefix of the\n\t\trelation rather than all of it. Null when nothing was truncated. A link cannot be paged,\n\t\tso a client that sees a name here must not write that relation back — the rows it never\n\t\treceived would be deleted.\n\t\t\"\"\"\n\t\ttruncatedLinks: [String!]\n\t}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\t\"\"\"\n\t\tWhether further records exist beyond this page. Always answered — it is read from the\n\t\tpage itself (one extra row is requested and discarded), so it costs no second query.\n\t\t\"\"\"\n\t\thasMore: Boolean!\n\t\t\"\"\"\n\t\tTotal matching the filters, ignoring limit/offset. Null unless the query asked for it\n\t\twith includeTotal, because counting is a full scan on most backends.\n\t\t\"\"\"\n\t\tcount: Int\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\t\"\"\"\n\t\tWhat the action's registered handler returned, verbatim, or the outcome the doctype declared.\n\t\t\"\"\"\n\t\tdata: JSON\n\t\terror: String\n\t\t\"\"\"\n\t\tThe record as stonecropRecord returns it after the action, whoever wrote it. The client stores\n\t\tthis, never data. Null when the action failed or targets no record.\n\t\t\"\"\"\n\t\trecord: JSON\n\t\t\"\"\"\n\t\tKeys the write discarded because the doctype declares no column for them, or because the\n\t\tvalue was a nested relation rather than a column value. Null when everything sent was\n\t\tstored. The action still succeeded — this is what it did not keep, and a client that\n\t\treports an unqualified success without checking it tells the user data was saved that\n\t\twas not.\n\t\t\"\"\"\n\t\tdroppedFields: [String!]\n\t}\n\n\textend type Query {\n\t\tstonecropMeta(doctype: String!): StonecropDoctypeMeta\n\t\tstonecropAllMeta: [StonecropDoctypeMeta!]!\n\t\tstonecropRecord(doctype: String!, id: String!, options: JSON): StonecropRecordResult\n\t\tstonecropRecords(\n\t\t\tdoctype: String!\n\t\t\tfilters: JSON\n\t\t\torderBy: String\n\t\t\tlimit: Int\n\t\t\toffset: Int\n\t\t\tincludeTotal: Boolean\n\t\t\toptions: JSON\n\t\t): StonecropRecordsResult\n\t}\n\n\textend type Mutation {\n\t\tstonecropAction(doctype: String!, action: String!, args: JSON): StonecropActionResult!\n\t}\n`\n","import type { DoctypeField, DoctypeMeta, LinkDeclaration, ValueField, GetRecordOptions } from '@stonecrop/schema'\nimport { camelToSnake, getRecordIdField, resolveLinkRenderMode, unwrapInlineLinks } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgCodec, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { createColumnReader } from '../columns'\nimport type { ColumnSelection } from '../columns'\nimport { columnBackedFields, flattenFields } from '../fields'\nimport { enrichLinkDisplayFields } from '../link-display'\nimport { resolveTableName } from '../tables'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta, validateReferences } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\n\n/**\n * Everything a server-side action handler is given when `stonecropAction` dispatches to it.\n *\n * A context object rather than positional parameters so the set can grow without breaking\n * registered handlers — the adapters that supply these live in consumer repositories.\n * @public\n */\nexport interface ActionHandlerContext {\n\t/**\n\t * Active database client for the current request. **It is inside the action's transaction.**\n\t *\n\t * The guard read, this handler, and the state write all run on this client inside one\n\t * transaction, so the action is atomic: throw, and everything this handler wrote is rolled\n\t * back along with the state change. Returning normally commits the lot.\n\t *\n\t * Do **not** open your own `BEGIN`/`COMMIT` around these statements. A `COMMIT` here would\n\t * close the action's transaction early, committing work the guard may still reject. If you\n\t * need to undo part of your own work without failing the action, use a `SAVEPOINT`.\n\t *\n\t * Work sent to a *different* connection is outside all of this and will not be rolled back —\n\t * so use this client rather than opening one of your own.\n\t *\n\t * Rows from a raw `pgClient.query()` carry snake_case **column** names, while the middleware's\n\t * own read paths alias them to camelCase fieldnames at the SQL layer (ADR 0004). A handler that\n\t * returns raw rows therefore leaks snake_case keys to the client. Alias in SQL\n\t * (`\"display_name\" AS \"displayName\"`) or convert with `snakeToCamel` from `@stonecrop/schema`.\n\t */\n\tpgClient: PgClient\n\t/** The doctype the action was dispatched against, as the client sent it. */\n\tdoctype: string\n\t/** The action's key in `workflow.actions` — the same string the handler was registered under. */\n\taction: string\n\t/** The resolved doctype metadata, for field names, the primary key, and the workflow. */\n\tmeta: DoctypeMeta\n\t/** The target record's identity, taken from the first argument envelope. Absent for a record-less command. */\n\trecordId?: string | number\n\t/**\n\t * The record field data the client sent (`args[0].data`).\n\t *\n\t * Unvalidated: `args` is an opaque `JSON` scalar, so this is browser-supplied input that has\n\t * passed through no schema. Treat it as untrusted — parameterize it into SQL and whitelist\n\t * the fields the action is allowed to touch.\n\t */\n\tdata: Record<string, unknown>\n\t/** The full argument envelope, for the actions that need more than the first record. */\n\targs: unknown[]\n\t/** The state the guard read, or `undefined` when nothing about the action required reading it. */\n\tcurrentState?: string\n}\n\n/**\n * A server-side effect for one doctype action, supplied by whoever owns the database.\n *\n * Throwing rejects the action and no state is written. The client stores the result's `record`,\n * the adapter's read of the record after the action, never this return; a return carrying the\n * doctype's declared key names the record read, which is how a handler that creates one says so.\n *\n * The return value is passed through verbatim as `StonecropActionResult.data`, so it must be\n * API-layer data — camelCase fieldname keys, not raw snake_case columns. See `pgClient` above and\n * ADR 0007.\n * @public\n */\nexport type ActionHandler = (context: ActionHandlerContext) => Promise<unknown>\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin.\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/**\n\t * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks\n\t * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.\n\t */\n\tdebug?: boolean\n\t/**\n\t * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.\n\t * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).\n\t * SQL fragments and subqueries are not supported.\n\t * When absent for a doctype, the table name is derived as `pascalToSnake(doctype.name)`, so\n\t * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a\n\t * PascalCase name: `camelToSnake('User')` is `_user`.)\n\t */\n\ttables?: Record<string, string>\n\t/**\n\t * Server-side effects for workflow actions, keyed `[doctype name][action key]`.\n\t *\n\t * This is the seam that makes a stateless Command executable. `applyGuardedTransition` can\n\t * apply a doctype's own outcome — a `nextState` transition, or a `selfTransition` data write —\n\t * but an action that is neither has nothing to apply and fails loudly. Registering a handler\n\t * here supplies the missing half.\n\t *\n\t * **The doctype never names a handler, and a handler never overrides the guard.** The two are\n\t * authored by different people: a doctype is runtime data edited in DocBuilder by whoever\n\t * models the workflow, while these run behind the GraphQL surface and belong to whoever owns\n\t * the database. So the doctype keeps `allowedStates` (may this run) and `nextState` (what state\n\t * results), and this keeps the effect (what actually happens). Routing between them is\n\t * resolved here, on the server, and is never published to the client.\n\t *\n\t * Handlers are looked up by `meta.name` — the doctype's canonical name, not its slug. An\n\t * unregistered action is not an error in itself: a transition needs no handler. It fails only\n\t * when the doctype gave the action no outcome either, and the error then names the action and\n\t * both ways to fix it, so a typo'd key reports as a missing effect rather than a silent no-op.\n\t *\n\t * @example\n\t * ```ts\n\t * createStonecropPlugin({\n\t * actionHandlers: {\n\t * Order: {\n\t * async recalculateTotal({ pgClient, recordId }) {\n\t * const { rows } = await pgClient.query({\n\t * text: 'UPDATE \"order\" SET total = (SELECT COALESCE(SUM(amount), 0) FROM order_item WHERE order_id = $1) WHERE id = $1 RETURNING *',\n\t * values: [recordId],\n\t * })\n\t * return rows[0]\n\t * },\n\t * },\n\t * },\n\t * })\n\t * ```\n\t */\n\tactionHandlers?: Record<string, Record<string, ActionHandler>>\n\t/**\n\t * Row cap applied when nothing else names one: to `stonecropRecords` when the caller requests\n\t * no `limit`, and to a many-side link when its declaration carries no `fetch.limit`. Defaults\n\t * to 200.\n\t *\n\t * A row cap is a statement about what this database can afford to serve, so it belongs to\n\t * whoever owns the database — not to a doctype (which describes the API surface, not the\n\t * table) and not to a page (which cannot know the size of an arbitrary table). Callers stay\n\t * free to ask for less; they cannot ask for an unbounded scan by omission.\n\t *\n\t * One number covers both reads because a link *is* a list, fetched a different way. It used to\n\t * be capped at a hard-coded 50 that no option could reach, which is how an operator watching a\n\t * slow query found there was no knob to turn.\n\t *\n\t * Truncation is always reported — `hasMore` for a list, `truncatedLinks` for a record — so a\n\t * partial answer is distinguishable from a complete one without asking for a count. That\n\t * matters more for a link than for a list: a link cannot be paged, so a client that writes\n\t * back a truncated relation deletes the rows it was never sent.\n\t *\n\t * Set to `null` for no default cap. That is the pre-0.17 behaviour for lists, and it means an\n\t * unqualified list query returns the whole table and a link returns the whole relation.\n\t */\n\tdefaultRecordLimit?: number | null\n}\n\n/**\n * Carries a reported failure out through a `throw`, purely so the transaction rolls back.\n *\n * `applyGuardedTransition` reports every failure as a return value, and a value returned from\n * inside `withTransaction` commits. This is the adapter between \"the action failed\" and \"undo it\"\n * that does not also turn a refused guard into a GraphQL error: the dispatcher unwraps it and\n * answers with the original envelope.\n */\nclass ActionRolledBack extends Error {\n\tconstructor(readonly outcome: { success: boolean; data: unknown; error: string | null }) {\n\t\tsuper(outcome.error ?? 'Action failed')\n\t\tthis.name = 'ActionRolledBack'\n\t}\n}\n\n/** One record a read is asked for: the arguments `stonecropRecord` takes. */\ninterface RecordReadSpec {\n\tdoctype: unknown\n\tid: unknown\n\toptions?: unknown\n}\n\n/** One record as `stonecropRecord` serves it. */\ninterface RecordReadResult {\n\tdata: Record<string, unknown> | null\n\tdoctype: string\n\tunknownLinks?: string[]\n\ttruncatedLinks?: string[]\n}\n\n/**\n * Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can\n * read it. An *expanding* link is a relation in the payload rather than a scalar, so `getColumnSelections`\n * omits its FK column by design — but the expansion needs the value to find the target. Aliasing\n * keeps that need from changing the payload: every alias is stripped before the record is returned.\n */\nconst LINK_FK_ALIAS = '__stonecropLinkFk_'\n\n/**\n * The column this adapter keeps a record's workflow state in.\n *\n * Named once because three statements depend on agreeing about it: the guard's `FOR UPDATE` read,\n * the transition's write, and the data write that must refuse to touch it. A patch that could set\n * this column would let any client walk past `allowedStates` by writing the very value the guard\n * reads.\n */\nconst STATE_COLUMN = 'status'\n\n/**\n * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.\n *\n * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`\n * during schema construction — it does not need to be supplied by the caller.\n *\n * @param options - Optional plugin configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createStonecropPlugin = (options: StonecropPluginOptions = {}): GraphileConfig.Plugin => {\n\t/**\n\t * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging\n\t * for queries that run inside custom loadOneWithPgClient callbacks, which\n\t * bypass the executor's native instrumentation.\n\t */\n\tconst debugSql = options.debug\n\t\t? <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? [])\n\t\t\t\treturn pgClient.query<T>(query)\n\t\t\t}\n\t\t: <T>(pgClient: PgClient, query: { text: string; values?: unknown[] }) => pgClient.query<T>(query)\n\n\t// Resolved once, for both read paths. `undefined` means \"not configured\" and `null` means\n\t// \"configured off\", which is a distinction `??` cannot make — and the two paths disagreeing\n\t// about it is exactly how a link came to be capped by a different number than a list.\n\tconst defaultRowLimit: number | null = options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit\n\n\tconst schemaPlugin = extendSchema(build => {\n\t\t// Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.\n\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- build.input.pgRegistry is a PostGraphile internal not in the public Build type\n\t\tconst pgRegistry = (build as any).input?.pgRegistry as\n\t\t\t| { pgExecutors?: Record<string, PgExecutor>; pgCodecs?: Record<string, PgCodec> }\n\t\t\t| undefined\n\t\tconst executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : undefined\n\t\tif (!executor) {\n\t\t\tthrow new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured')\n\t\t}\n\t\tconst columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables)\n\n\t\t// Schema build is the one point where both the registry and the plugin's options are in\n\t\t// hand, so it is where a stale registration can be caught before it silently no-ops.\n\t\tif (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers)\n\t\tassertReferencesResolve()\n\n\t\t/** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */\n\t\tconst readRecords = async (pgClient: PgClient, specs: readonly RecordReadSpec[]): Promise<RecordReadResult[]> => {\n\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t}\n\n\t\t\tconst results: RecordReadResult[] = Array.from({ length: specs.length })\n\n\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\tif (!meta) {\n\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Not `data: null` — that is the answer for a record that does not exist, and a\n\t\t\t\t// doctype nobody can look up is a misconfiguration, not an empty result.\n\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(doctype)\n\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t// Resolved once per doctype: how each link renders, and which foreign keys the\n\t\t\t\t// SELECT must carry for the expansion below to work at all.\n\t\t\t\t//\n\t\t\t\t// `resolveLinkRenderMode` needs the linked field's own component, so the fields\n\t\t\t\t// are indexed by name — flattened, because a link's field may sit inside a\n\t\t\t\t// fieldset and `getColumnSelections` already descends to select it.\n\t\t\t\tconst fieldByName = new Map(flattenFields(meta.fields).map(f => [f.fieldname, f]))\n\t\t\t\tconst linkFkAliases: Array<{ fieldname: string; alias: string }> = []\n\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links ?? {})) {\n\t\t\t\t\t// Many-side links find their rows by a column on the *target*; only a one-side\n\t\t\t\t\t// link reads a foreign key off this row.\n\t\t\t\t\tif (link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne') continue\n\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t// An inline link keeps its FK as a scalar, so `getColumnSelections` already selected\n\t\t\t\t\t// it under its own name and no alias is needed.\n\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\t\t\t\t\tlinkFkAliases.push({ fieldname, alias: `${LINK_FK_ALIAS}${fieldname}` })\n\t\t\t\t}\n\t\t\t\tconst select = columns.select(meta.name, [\n\t\t\t\t\t...getColumnSelections(meta),\n\t\t\t\t\t...linkFkAliases.map(({ fieldname, alias }) => ({ column: camelToSnake(fieldname), alias })),\n\t\t\t\t])\n\n\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\tvalues: [ids],\n\t\t\t\t})\n\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t// A declared key the database does not actually enforce as unique collapses several\n\t\t\t\t// rows into that Map, and it keeps whichever came last — one arbitrary record,\n\t\t\t\t// returned as though it were *the* record, with nothing to say so. Refuse instead.\n\t\t\t\t//\n\t\t\t\t// This is exact rather than a proxy for the problem: `ANY` matches each requested id\n\t\t\t\t// once, so a shortfall here means two distinct rows genuinely share a key value. A\n\t\t\t\t// `pg_index` check would instead ask whether a unique constraint exists, which is the\n\t\t\t\t// cause rather than the harm — and would flag a column that is unique in practice but\n\t\t\t\t// unconstrained, which is a real and common shape.\n\t\t\t\tif (rows.length !== rowByPk.size) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Doctype \"${doctype}\" declares \"${pkMeta.fieldname}\" as its identity, but that column ` +\n\t\t\t\t\t\t\t`is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows ` +\n\t\t\t\t\t\t\t`matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. ` +\n\t\t\t\t\t\t\t`Declare a field that uniquely identifies a record, or add a unique constraint.`\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\t// Collected across the batch so the display lookup runs once for all of them.\n\t\t\t\t// Called per row inside this loop it issued one query per record per link field,\n\t\t\t\t// which is the N+1 this batched loader exists to avoid — and silently, since the\n\t\t\t\t// enriched rows come out identical either way.\n\t\t\t\tconst enrichedRows: Record<string, unknown>[] = []\n\n\t\t\t\tfor (const i of indices) {\n\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tresults[i] = { data: null, doctype }\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\tenrichedRows.push(rowData)\n\t\t\t\t\t// Per record, not per doctype: two records of one doctype can differ in whether\n\t\t\t\t\t// a relation overflowed, and a shared list would report the wrong one truncated.\n\t\t\t\t\tconst truncatedLinks: string[] = []\n\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null\n\n\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t// The payload key is the *resolved* fieldname, not the map key: the client\n\t\t\t\t\t\t\t// binds a link to the field named `link.fieldname ?? key` and reads the\n\t\t\t\t\t\t\t// nested data off that field, so writing under the bare key put the result\n\t\t\t\t\t\t\t// somewhere nothing looks whenever a declaration named its own `fieldname`.\n\t\t\t\t\t\t\t// Identical for every declaration that omits `fieldname`, which is all of them\n\t\t\t\t\t\t\t// in this repo — hence latent until now.\n\t\t\t\t\t\t\tconst fieldname = link.fieldname ?? linkName\n\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t// Two questions, kept apart. `method === 'sync'` is a *type narrowing* — only\n\t\t\t\t\t\t\t// `SyncFetch` carries a `limit` — and the server default used to hang off its\n\t\t\t\t\t\t\t// `else`, so declaring the method a many-side link already defaults to removed\n\t\t\t\t\t\t\t// the cap entirely. \"Did the author write a limit?\" and \"did the author write\n\t\t\t\t\t\t\t// the word sync?\" are now asked separately.\n\t\t\t\t\t\t\tconst declaredLimit = fetch?.method === 'sync' ? fetch.limit : undefined\n\t\t\t\t\t\t\tconst effectiveLimit = isMany ? (declaredLimit ?? defaultRowLimit) : undefined\n\n\t\t\t\t\t\t\t// The one gate. It used to be followed by a second test that re-asked the\n\t\t\t\t\t\t\t// same question using only `includeSet` — `null` for the boolean form — so\n\t\t\t\t\t\t\t// `includeNested: true` admitted every link here and then silently dropped\n\t\t\t\t\t\t\t// each non-`sync` one, handing back a partial record with no way to tell.\n\t\t\t\t\t\t\t// That test was redundant wherever it was correct: with a name list this gate\n\t\t\t\t\t\t\t// has already required membership, and without one it has already required\n\t\t\t\t\t\t\t// `sync`, so it could only ever fire in the boolean case it got wrong.\n\t\t\t\t\t\t\tconst shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\t\t\t// TODO(perf): custom link handlers per-row could run in parallel; needs collecting all custom handlers before await\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- custom handler per link; see TODO above\n\t\t\t\t\t\t\t\t\trowData[fieldname] = await handler(pgClient, rowData, link)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// `resolveLinkRenderMode` is the single definition of whether a link expands,\n\t\t\t\t\t\t\t// and this loop was the one caller that never asked it. An `inline` link is a\n\t\t\t\t\t\t\t// picker: the field holds its own id and the client resolves display text\n\t\t\t\t\t\t\t// separately, so expanding it here overwrote that id with the whole target\n\t\t\t\t\t\t\t// record and left the picker with an object it cannot render.\n\t\t\t\t\t\t\tif (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === 'inline') continue\n\n\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\tconst targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta))\n\n\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\t\t\t\t\t// Same reason the list path orders: a capped relation without a fixed order\n\t\t\t\t\t\t\t\t// returns an arbitrary subset of the children, and a different one each time\n\t\t\t\t\t\t\t\t// a child row is updated. `truncatedLinks` says the tail was cut; it cannot\n\t\t\t\t\t\t\t\t// say the head kept changing. Skipped when the target declares no identity —\n\t\t\t\t\t\t\t\t// there is no stable key to order by, and inventing one would be a guess.\n\t\t\t\t\t\t\t\tconst linkPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (linkPkMeta) {\n\t\t\t\t\t\t\t\t\tsql += ` ORDER BY \"${camelToSnake(linkPkMeta.fieldname)}\" ASC`\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t// One row more than the cap, same probe the list path uses: its presence\n\t\t\t\t\t\t\t\t\t// is the whole truncation answer and costs no second query.\n\t\t\t\t\t\t\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// TODO(perf): many-side link queries per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one SQL per backlink per row; see TODO above\n\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\tvalues: linkValues,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\t// A truncated relation that says nothing is how a read-modify-write deletes\n\t\t\t\t\t\t\t\t// the tail: the client cannot tell 50 rows from all of them, so it writes\n\t\t\t\t\t\t\t\t// back what it was given. Reported for every source of truncation, the\n\t\t\t\t\t\t\t\t// author's `fetch.limit` included — that one is just as silent.\n\t\t\t\t\t\t\t\tif (effectiveLimit != null && linked.length > effectiveLimit) {\n\t\t\t\t\t\t\t\t\ttruncatedLinks.push(fieldname)\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked.slice(0, effectiveLimit)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = linked\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read from the reserved alias, never the fieldname: an expanding link's FK\n\t\t\t\t\t\t\t\t// column is deliberately absent from `getColumnSelections`, so the plain read found\n\t\t\t\t\t\t\t\t// `undefined` on every record and answered `null` — a relation that looked\n\t\t\t\t\t\t\t\t// permanently empty rather than one nobody had asked the right question for.\n\t\t\t\t\t\t\t\tconst fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`]\n\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\trowData[fieldname] = null\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// `continue` here would drop the link from the payload, which reads to the\n\t\t\t\t\t\t\t\t// client as \"this record has no such relation\" rather than \"its target\n\t\t\t\t\t\t\t\t// cannot be identified\".\n\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\tif (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name)\n\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\t\t// TODO(perf): one-side link FK lookups per row could be parallelized; needs collecting across links before await\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- one FK lookup per link per row; see TODO above\n\t\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\tvalues: [fkValue],\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\ttargetSelect.decodeRows(linked)\n\t\t\t\t\t\t\t\trowData[fieldname] = linked[0] ?? null\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// The aliases are a read channel for this loop, not part of the record. Stripped\n\t\t\t\t\t// unconditionally so a link that was never expanded cannot leak its raw FK into a\n\t\t\t\t\t// payload that has otherwise always described that relation as a nested object.\n\t\t\t\t\tfor (const { alias } of linkFkAliases) delete rowData[alias]\n\n\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\ttruncatedLinks: truncatedLinks.length ? truncatedLinks : undefined,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// After the expansion loop, not before it: a link that expanded has replaced its\n\t\t\t\t// scalar FK with an object, and enrichment skips those. Running first stamped a\n\t\t\t\t// display value beside a relation that no longer had an id to display.\n\t\t\t\t//\n\t\t\t\t// Sequential per doctype group because `pgClient` is one checked-out connection,\n\t\t\t\t// so awaiting these together would only queue them inside the driver.\n\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop\n\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql)\n\t\t\t}\n\n\t\t\treturn results\n\t\t}\n\n\t\treturn {\n\t\t\ttypeDefs,\n\n\t\t\tobjects: {\n\t\t\t\tQuery: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropMeta(_: any, { $doctype }: any) {\n\t\t\t\t\t\t\treturn lambda($doctype, (doctype: unknown) => {\n\t\t\t\t\t\t\t\tconst meta = getMeta(String(doctype))\n\t\t\t\t\t\t\t\treturn meta ?? null\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropAllMeta() {\n\t\t\t\t\t\t\treturn constant(getAllMeta())\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecord(_: any, { $doctype, $id, $options }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, id: $id, options: $options }),\n\t\t\t\t\t\t\t\treadRecords\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }: any) {\n\t\t\t\t\t\t\treturn loadOneWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({\n\t\t\t\t\t\t\t\t\tdoctype: $doctype,\n\t\t\t\t\t\t\t\t\tfilters: $filters,\n\t\t\t\t\t\t\t\t\torderBy: $orderBy,\n\t\t\t\t\t\t\t\t\tlimit: $limit,\n\t\t\t\t\t\t\t\t\toffset: $offset,\n\t\t\t\t\t\t\t\t\tincludeTotal: $includeTotal,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\treturn await Promise.all(\n\t\t\t\t\t\t\t\t\t\tspecs.map(async spec => {\n\t\t\t\t\t\t\t\t\t\t\tconst doctype = String(spec.doctype)\n\t\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\t\t// An unknown doctype answers \"no records\" rather than erroring, so a caller\n\t\t\t\t\t\t\t\t\t\t\t\t// who asked for a total gets 0. Returning null here would make null mean\n\t\t\t\t\t\t\t\t\t\t\t\t// two things — \"you did not ask\" and \"I could not say\" — and a client\n\t\t\t\t\t\t\t\t\t\t\t\t// cannot tell those apart.\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype, hasMore: false, count: spec.includeTotal === true ? 0 : null }\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst knownFields = new Set(flattenFields(meta.fields).map(f => f.fieldname))\n\t\t\t\t\t\t\t\t\t\t\tconst select = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection). Built once for\n\t\t\t\t\t\t\t\t\t\t\t// the page and its total, which must count the rows the page is drawn from.\n\t\t\t\t\t\t\t\t\t\t\tconst filterValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\tconst whereClauses: string[] = []\n\t\t\t\t\t\t\t\t\t\t\tif (spec.filters != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.filters is a Grafast runtime value; shape guaranteed by GraphQL schema\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [field, value] of Object.entries(spec.filters as Record<string, unknown>)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(field)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown filter field: ${field} for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\tfilterValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst column = camelToSnake(field)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t`\"${column}\" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = [...filterValues]\n\n\t\t\t\t\t\t\t\t\t\t\t// ORDER BY (field name whitelisted — column names cannot be parameterised)\n\t\t\t\t\t\t\t\t\t\t\tlet orderByClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (spec.orderBy != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (typeof spec.orderBy !== 'string')\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`)\n\t\t\t\t\t\t\t\t\t\t\t\tconst orderByStr = spec.orderBy\n\t\t\t\t\t\t\t\t\t\t\t\tconst lastUnder = orderByStr.lastIndexOf('_')\n\t\t\t\t\t\t\t\t\t\t\t\tif (lastUnder <= 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy format: \"${orderByStr}\". Expected FIELD_ASC or FIELD_DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst dir = orderByStr.slice(lastUnder + 1).toUpperCase()\n\t\t\t\t\t\t\t\t\t\t\t\tif (dir !== 'ASC' && dir !== 'DESC') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid orderBy direction: \"${dir}\". Must be ASC or DESC`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\tconst fieldName = orderByStr.slice(0, lastUnder)\n\t\t\t\t\t\t\t\t\t\t\t\tif (!knownFields.has(fieldName)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Unknown orderBy field: \"${fieldName}\" for doctype ${meta.name}`)\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(fieldName)}\" ${dir}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// A page is only meaningful against a fixed order, and LIMIT/OFFSET without one\n\t\t\t\t\t\t\t\t\t\t\t// is two independent scans of heap order — an UPDATE between them moves that row\n\t\t\t\t\t\t\t\t\t\t\t// to the tail, so the row it displaced is never returned and nothing in the\n\t\t\t\t\t\t\t\t\t\t\t// payload says a record was skipped. The declared identity is the right default\n\t\t\t\t\t\t\t\t\t\t\t// because it is unique: it gives a total order, which is what makes page 2 start\n\t\t\t\t\t\t\t\t\t\t\t// exactly where page 1 stopped.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Only when the doctype declares an identity. Without one there is no stable key\n\t\t\t\t\t\t\t\t\t\t\t// to order by, and inventing one here would be a guess; such a doctype cannot be\n\t\t\t\t\t\t\t\t\t\t\t// paged stably by any means.\n\t\t\t\t\t\t\t\t\t\t\tif (orderByClause === '') {\n\t\t\t\t\t\t\t\t\t\t\t\tconst listPkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\t\t\tif (listPkMeta) {\n\t\t\t\t\t\t\t\t\t\t\t\t\torderByClause = ` ORDER BY \"${camelToSnake(listPkMeta.fieldname)}\" ASC`\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// LIMIT / OFFSET. A caller that names no limit gets the configured default rather\n\t\t\t\t\t\t\t\t\t\t\t// than the whole table: omission is how an unbounded scan used to happen, and the\n\t\t\t\t\t\t\t\t\t\t\t// only guard against it lived in the scaffold's fetch helper, which is neither the\n\t\t\t\t\t\t\t\t\t\t\t// right layer nor present in a host that wrote its own.\n\t\t\t\t\t\t\t\t\t\t\t// Grafast passes arguments through as loosely-typed runtime values, so narrow\n\t\t\t\t\t\t\t\t\t\t\t// before doing arithmetic on this — same reason orderBy is validated above.\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null && typeof spec.limit !== 'number') {\n\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(`Invalid limit: expected number, got ${typeof spec.limit}`)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit: number | null = spec.limit ?? defaultRowLimit\n\t\t\t\t\t\t\t\t\t\t\tlet pagingClause = ''\n\t\t\t\t\t\t\t\t\t\t\tif (effectiveLimit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t// One more row than asked for. Its presence is the whole `hasMore` answer, and\n\t\t\t\t\t\t\t\t\t\t\t\t// it is discarded below — this is why knowing a list is truncated costs no\n\t\t\t\t\t\t\t\t\t\t\t\t// second query, where a COUNT(*) would be a full scan on every list read.\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(effectiveLimit + 1)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` LIMIT $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tif (spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.offset)\n\t\t\t\t\t\t\t\t\t\t\t\tpagingClause += ` OFFSET $${values.length}`\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\tselect.decodeRows(rows)\n\n\t\t\t\t\t\t\t\t\t\t\t// The extra row requested above is a probe, not data. Its presence is what makes\n\t\t\t\t\t\t\t\t\t\t\t// a capped page distinguishable from a complete table; trim it before anything\n\t\t\t\t\t\t\t\t\t\t\t// downstream can mistake it for a record.\n\t\t\t\t\t\t\t\t\t\t\tconst hasMore = effectiveLimit != null && rows.length > effectiveLimit\n\t\t\t\t\t\t\t\t\t\t\tconst data = [...(hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows)]\n\n\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql)\n\n\t\t\t\t\t\t\t\t\t\t\t// Total matching the filters, independent of LIMIT/OFFSET, and opt-in.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Explicitly requested rather than inferred from whether `count` was selected:\n\t\t\t\t\t\t\t\t\t\t\t// this resolver is a Grafast plan step and receives only its arguments, never the\n\t\t\t\t\t\t\t\t\t\t\t// selection set, and making the plan vary by selection is what Grafast optimises\n\t\t\t\t\t\t\t\t\t\t\t// against. An argument also puts the cost in the query the client wrote.\n\t\t\t\t\t\t\t\t\t\t\tlet count: number | null = null\n\t\t\t\t\t\t\t\t\t\t\tif (spec.includeTotal === true) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows: countRows } = await debugSql<{ row_count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: filterValues,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\tcount = parseInt(countRows[0]?.row_count ?? '0', 10)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\treturn { data, doctype, hasMore, count }\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tMutation: {\n\t\t\t\t\tplans: {\n\t\t\t\t\t\tstonecropAction(_: any, { $doctype, $action, $args: $actionArgs }: any) {\n\t\t\t\t\t\t\treturn sideEffectWithPgClient(\n\t\t\t\t\t\t\t\texecutor,\n\t\t\t\t\t\t\t\tobject({ doctype: $doctype, action: $action, actionArgs: $actionArgs }),\n\t\t\t\t\t\t\t\tasync (pgClient: PgClient, spec: any) => {\n\t\t\t\t\t\t\t\t\tconst meta = getMeta(String(spec.doctype))\n\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown doctype: ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst actionDef = meta.workflow?.actions?.[spec.action]\n\t\t\t\t\t\t\t\t\tif (!actionDef) {\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: `Unknown action: ${spec.action} on ${spec.doctype}`,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst table = resolveTableName(meta.name, options.tables)\n\t\t\t\t\t\t\t\t\t// Resolved lazily: only a state read or write needs the key column. A\n\t\t\t\t\t\t\t\t\t// record-less command reaches its handler on a doctype that declares no\n\t\t\t\t\t\t\t\t\t// primary key, which an eager check would refuse for no reason.\n\t\t\t\t\t\t\t\t\tconst pkColumn = () => {\n\t\t\t\t\t\t\t\t\t\tconst pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\t\tif (!pkMeta) throw unresolvableIdentityError(String(spec.doctype))\n\t\t\t\t\t\t\t\t\t\treturn camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// Record envelope: [{ id, data }] — the transition keys off the record id.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- spec.actionArgs is a Grafast runtime value; record envelope shape is the dispatch contract\n\t\t\t\t\t\t\t\t\tconst rawArgs = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []) as Array<{\n\t\t\t\t\t\t\t\t\t\tid?: string | number\n\t\t\t\t\t\t\t\t\t\tdata?: Record<string, unknown>\n\t\t\t\t\t\t\t\t\t}>\n\t\t\t\t\t\t\t\t\t// An inline link arrives as `{ id, displayText }`; a column takes the id alone.\n\t\t\t\t\t\t\t\t\t// Reduced here so no client has to know what storage accepts.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The whole envelope, not just `recordData` below — handlers read `ctx.args`.\n\t\t\t\t\t\t\t\t\t// Copied, not mutated: `spec.actionArgs` is the request's own value.\n\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line oxc/no-map-spread\n\t\t\t\t\t\t\t\t\tconst argList = rawArgs.map(entry =>\n\t\t\t\t\t\t\t\t\t\tentry?.data ? { ...entry, data: unwrapInlineLinks(meta.fields, entry.data) } : entry\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tconst recordId = argList[0]?.id\n\t\t\t\t\t\t\t\t\tconst recordData = argList[0]?.data ?? {}\n\n\t\t\t\t\t\t\t\t\t// The database author's effect for this action, if one is registered. Keyed\n\t\t\t\t\t\t\t\t\t// by the doctype's canonical name so a slug-resolved lookup above cannot\n\t\t\t\t\t\t\t\t\t// silently miss it.\n\t\t\t\t\t\t\t\t\tconst handler = options.actionHandlers?.[meta.name]?.[String(spec.action)]\n\n\t\t\t\t\t\t\t\t\t// What a data write is allowed to set. Column identifiers come from the\n\t\t\t\t\t\t\t\t\t// doctype and never from the request — `args` is an opaque JSON scalar, so\n\t\t\t\t\t\t\t\t\t// every key in `data` is browser-supplied — which is what makes it safe to\n\t\t\t\t\t\t\t\t\t// build SQL from a patch at all.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// The same derivation the read path uses, so what a record exposes is what a\n\t\t\t\t\t\t\t\t\t// record accepts. `status` is removed because state is the workflow's to\n\t\t\t\t\t\t\t\t\t// move, never the patch's. A column the database fills itself is refused in\n\t\t\t\t\t\t\t\t\t// `partitionPatch`, which asks the table only when there is a row to write:\n\t\t\t\t\t\t\t\t\t// this map is built for every action, including one on a doctype with no table.\n\t\t\t\t\t\t\t\t\tconst writable = new Map(\n\t\t\t\t\t\t\t\t\t\tcolumnBackedFields(meta.fields)\n\t\t\t\t\t\t\t\t\t\t\t.filter(f => camelToSnake(f.fieldname) !== STATE_COLUMN)\n\t\t\t\t\t\t\t\t\t\t\t.map(f => [f.fieldname, f] as const)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Whether this doctype has a workflow state to read at all. Derived from the\n\t\t\t\t\t\t\t\t\t// same declarations, so the guard cannot look for a column the doctype's own\n\t\t\t\t\t\t\t\t\t// API surface does not describe.\n\t\t\t\t\t\t\t\t\tconst declaresState = columnBackedFields(meta.fields).some(\n\t\t\t\t\t\t\t\t\t\tf => camelToSnake(f.fieldname) === STATE_COLUMN\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t// Reported on the result rather than logged: a dropped key is data the user\n\t\t\t\t\t\t\t\t\t// believes was saved, which is the same data-loss signal `truncatedLinks`\n\t\t\t\t\t\t\t\t\t// carries for a truncated read.\n\t\t\t\t\t\t\t\t\tconst droppedFields: string[] = []\n\t\t\t\t\t\t\t\t\tconst partitionPatch = (patch: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\t\t\tconst cols: string[] = []\n\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\t\t\t\t\t\t\t\t\t\tfor (const [key, value] of Object.entries(patch)) {\n\t\t\t\t\t\t\t\t\t\t\tif (!writable.has(key) || !columns.writable(meta.name, camelToSnake(key))) {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t// An expanding link reads back as a nested record while its column\n\t\t\t\t\t\t\t\t\t\t\t// holds a scalar foreign key, so a read-modify-write hands this loop\n\t\t\t\t\t\t\t\t\t\t\t// an object bound for a uuid column. The name resolving is not\n\t\t\t\t\t\t\t\t\t\t\t// enough; the shape has to match a column value too.\n\t\t\t\t\t\t\t\t\t\t\tif (value !== null && typeof value === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\tdroppedFields.push(key)\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\tcols.push(camelToSnake(key))\n\t\t\t\t\t\t\t\t\t\t\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\treturn { cols, values }\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// One transaction spans the guard read, the effect and the state write, so an\n\t\t\t\t\t\t\t\t\t// action either lands whole or not at all. `withTransaction` issues `begin` at\n\t\t\t\t\t\t\t\t\t// the top level and a `savepoint` if something upstream already opened one, so\n\t\t\t\t\t\t\t\t\t// nesting is safe rather than something callers must avoid.\n\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t// Every statement below runs on `tx`, not on the outer client. Work sent to the\n\t\t\t\t\t\t\t\t\t// outer client — or to a connection a handler opens itself — is outside this\n\t\t\t\t\t\t\t\t\t// transaction and would survive a rollback.\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await pgClient.withTransaction(async (tx: PgClient) => {\n\t\t\t\t\t\t\t\t\t\t\tconst outcome = await applyGuardedTransition(\n\t\t\t\t\t\t\t\t\t\t\t\tactionDef,\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No id in the envelope means no record was targeted at all, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the same answer as a lookup that misses: `null`, not `undefined`.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Selecting `status` unconditionally made this read fail outright on\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// any table without that column — and a self-transition reaches here\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// not to read a state but to learn whether the row exists, which is\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// what decides create vs. update. So the projection follows the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// doctype: a doctype that declares no state field has none to read,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and the honest answer for a row it finds is \"exists, no state\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// (Measured: 24 of FAB's 35 guarded tables have no `status` column.)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst projection = declaresState ? `\"${STATE_COLUMN}\"` : `\"${pkColumn()}\"`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// FOR UPDATE holds the row until this transaction ends, so a second\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// action on the same record waits rather than reading the same state\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// and acting on it too. Without it the guard is a check-then-act\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// race: two concurrent approvals both read PENDING and both proceed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, string | null>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${projection} FROM ${table} WHERE \"${pkColumn()}\"::text = $1 FOR UPDATE`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No row at all vs. a row whose `status` is NULL — see GuardedTransitionIO.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (rows.length === 0) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!declaresState) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0][STATE_COLUMN] ?? undefined\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteState: async (nextState: string) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tawait debugSql(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"${STATE_COLUMN}\" = $1 WHERE \"${pkColumn()}\"::text = $2`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [nextState, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t// The upsert, and the only write path for record data. `exists`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// comes from the guard's own read, so no second lookup decides it.\n\t\t\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t\t\t// Returns the same projection the read path selects, never\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `RETURNING *`: raw columns come back snake_case, and the client\n\t\t\t\t\t\t\t\t\t\t\t\t\t// resolves identity by the *declared fieldname*. A doctype keyed\n\t\t\t\t\t\t\t\t\t\t\t\t\t// `itemId` would receive `item_id`, find no identity, and file a\n\t\t\t\t\t\t\t\t\t\t\t\t\t// created record nowhere — which is that exact bug, already once\n\t\t\t\t\t\t\t\t\t\t\t\t\t// shipped and patched downstream.\n\t\t\t\t\t\t\t\t\t\t\t\t\twriteData: async (patch: Record<string, unknown>, exists: boolean) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { cols, values } = partitionPatch(patch)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst returning = columns.select(meta.name, getColumnSelections(meta))\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Creating is what the *absence* of an id means. An id that was\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dispatched and matched nothing is a record that has gone away\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// since the client read it, and treating that as a create mints a\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// second row under a new identity while the client believes it\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// updated the first — a lost update that reports success.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// The dispatcher cannot make this call: it never receives the id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// deliberately, since identity is the backend's business. So the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// distinction its `readState` contract collapses is restored here,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// where the id is in scope.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (recordId != null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`Action \"${actionDef.label ?? spec.action}\" targets ${meta.name} \"${String(recordId)}\", ` +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`which no longer exists. Nothing was created — a record dispatched with an ` +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`identity is an update, and creating one is what dispatching no identity means.`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// No identity is minted here. A declared key present in the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// patch is a natural key the user filled in and passes\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// through the whitelist like any other column; absent, the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// column default supplies it. Either way the row states its\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// own identity back.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst text = cols.length\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? `INSERT INTO ${table} (${cols.map(c => `\"${c}\"`).join(', ')}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(', ')}) RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, { text, values })\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Nothing writable survived the patch. `SET` with no assignments\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// is a syntax error, and reporting failure would be wrong — the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// record is fine, it just has no new data. Read it back so the\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// client still gets the record, with `droppedFields` saying why\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// nothing changed.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (cols.length === 0) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${returning.list} FROM ${table} WHERE \"${pkColumn()}\"::text = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst assignments = cols\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.map((c, i) => `\"${c}\" = ${columns.bind(meta.name, c, `$${i + 1}`)}`)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.join(', ')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<Record<string, unknown>>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET ${assignments} WHERE \"${pkColumn()}\"::text = $${cols.length + 1} RETURNING ${returning.list}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [...values, String(recordId)],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturning.decodeRows(rows)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0] ?? {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\trunEffect: handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? (currentState: string | undefined) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thandler({\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpgClient: tx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoctype: String(spec.doctype),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taction: String(spec.action),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmeta,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trecordId,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata: recordData,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\targs: argList,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrentState,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t// The patch a self-transition persists. This adapter never passed it, which\n\t\t\t\t\t\t\t\t\t\t\t\t// was moot while it had no `writeData` — nothing consumed it. Wiring the write\n\t\t\t\t\t\t\t\t\t\t\t\t// without this argument saves an empty record and reports success.\n\t\t\t\t\t\t\t\t\t\t\t\trecordData\n\t\t\t\t\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t// `applyGuardedTransition` REPORTS failure, it does not throw — a refused\n\t\t\t\t\t\t\t\t\t\t\t// guard and a handler that blew up both come back as `{ success: false }`.\n\t\t\t\t\t\t\t\t\t\t\t// Returning that normally would commit the transaction, so a handler that\n\t\t\t\t\t\t\t\t\t\t\t// wrote three rows and then threw would keep all three. Throwing here is\n\t\t\t\t\t\t\t\t\t\t\t// what makes the rollback happen; the envelope is carried across so the\n\t\t\t\t\t\t\t\t\t\t\t// caller still gets `success: false` rather than a GraphQL error.\n\t\t\t\t\t\t\t\t\t\t\tif (!outcome.success) throw new ActionRolledBack(outcome)\n\t\t\t\t\t\t\t\t\t\t\t// A record a write returns is a record, so it carries the links a read\n\t\t\t\t\t\t\t\t\t\t\t// resolves. Enriching one path and not the other changes a record's\n\t\t\t\t\t\t\t\t\t\t\t// shape depending on how the client came by it: a link rendered its\n\t\t\t\t\t\t\t\t\t\t\t// display text until the record was saved, and its raw id from then\n\t\t\t\t\t\t\t\t\t\t\t// until the next full fetch. Nothing fails — the field just goes wrong.\n\t\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t\t// Runs inside the transaction so the lookup sees the row just written,\n\t\t\t\t\t\t\t\t\t\t\t// and only on success, since a rolled-back action returns no record.\n\t\t\t\t\t\t\t\t\t\t\t// A result that is not a record at all — an effect's `{ state }` — has\n\t\t\t\t\t\t\t\t\t\t\t// no field the doctype declares as an inline link, so it is untouched.\n\t\t\t\t\t\t\t\t\t\t\tif (outcome.success && outcome.data !== null && typeof outcome.data === 'object') {\n\t\t\t\t\t\t\t\t\t\t\t\t// A predicate rather than an assertion: an element that is not an object has\n\t\t\t\t\t\t\t\t\t\t\t\t// no field to enrich, so dropping it is the honest answer.\n\t\t\t\t\t\t\t\t\t\t\t\tconst written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t(row: unknown): row is Record<string, unknown> => row !== null && typeof row === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\tawait enrichLinkDisplayFields(tx, meta, written, columns, debugSql)\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\t// The record as a read returns it, whoever wrote it: the client files this,\n\t\t\t\t\t\t\t\t\t\t\t// never `data`, which stays the handler's own. Keyed by the declared identity\n\t\t\t\t\t\t\t\t\t\t\t// the reply states when it states one, since an action may create or re-key\n\t\t\t\t\t\t\t\t\t\t\t// the record, and by the dispatched id otherwise.\n\t\t\t\t\t\t\t\t\t\t\tconst pkField = getPkMeta(meta)?.fieldname\n\t\t\t\t\t\t\t\t\t\t\tconst repliedId: unknown =\n\t\t\t\t\t\t\t\t\t\t\t\tpkField !== undefined && outcome.data !== null && typeof outcome.data === 'object'\n\t\t\t\t\t\t\t\t\t\t\t\t\t? Reflect.get(outcome.data, pkField)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined\n\t\t\t\t\t\t\t\t\t\t\tconst readId = repliedId ?? recordId\n\t\t\t\t\t\t\t\t\t\t\tconst record =\n\t\t\t\t\t\t\t\t\t\t\t\treadId == null\n\t\t\t\t\t\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t\t\t\t\t\t: ((await readRecords(tx, [{ doctype: meta.name, id: readId }]))[0]?.data ?? null)\n\n\t\t\t\t\t\t\t\t\t\t\t// Attached here rather than carried through `applyGuardedTransition`:\n\t\t\t\t\t\t\t\t\t\t\t// which keys a backend can store is a storage question, and the\n\t\t\t\t\t\t\t\t\t\t\t// dispatcher is deliberately storage-agnostic. A failed action wrote\n\t\t\t\t\t\t\t\t\t\t\t// nothing, so the list is only meaningful on success.\n\t\t\t\t\t\t\t\t\t\t\tconst reply = { ...outcome, record }\n\t\t\t\t\t\t\t\t\t\t\treturn droppedFields.length ? { ...reply, droppedFields } : reply\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\t\tif (err instanceof ActionRolledBack) return err.outcome\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\n\treturn {\n\t\t...schemaPlugin,\n\t\tgather: {\n\t\t\thooks: {\n\t\t\t\t// Marks a column Postgres generates as neither insertable nor updatable, as PostGraphile\n\t\t\t\t// itself marks an identity generated always. PostGraphile reads `attgenerated` only into\n\t\t\t\t// `hasDefault`, which a plain default shares, so without this the data write cannot tell\n\t\t\t\t// the two apart. On the adapter's plugin rather than the preset, so it holds wherever the\n\t\t\t\t// write runs.\n\t\t\t\tpgCodecs_attribute(_info, event) {\n\t\t\t\t\tconst { attgenerated } = event.pgAttribute\n\t\t\t\t\tif (attgenerated == null || attgenerated === '') return\n\t\t\t\t\tevent.attribute.extensions ??= {}\n\t\t\t\t\tevent.attribute.extensions.isInsertable = false\n\t\t\t\t\tevent.attribute.extensions.isUpdatable = false\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Derive column selections from a flat field array.\n * Skips non-scalar fields (kind !== 'field'), `computed` fields\n * (no backing DB column), and *expanding* links\n * (relations fetched separately, not scalar columns on this table).\n */\nfunction collectColumns(fields: DoctypeField[], links: Map<string, LinkDeclaration>): ColumnSelection[] {\n\tconst columns: ColumnSelection[] = []\n\tfor (const f of columnBackedFields(fields)) {\n\t\t// Only an *expanding* link is a relation rather than a column. An inline link (a picker)\n\t\t// keeps its FK on this table and must still be selected — `resolveLinkRenderMode` is the\n\t\t// rule both sides of the wire share; never re-derive it here.\n\t\tconst link = links.get(f.fieldname)\n\t\tif (link && resolveLinkRenderMode(link, f.component) !== 'inline') continue\n\t\tcolumns.push({ column: camelToSnake(f.fieldname), alias: f.fieldname })\n\t}\n\treturn columns\n}\n\n/**\n * Derive the columns a record payload selects from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, and keeps\n * the fieldname as its alias so result rows carry API-layer keys.\n * Excludes `computed` fields (no backing DB column), Fieldset\n * containers (recursing into their children instead), and *expanding* links\n * (relations fetched separately). An inline link keeps its FK column here.\n *\n * Exported for unit testing (not re-exported from the package index).\n */\nexport function getColumnSelections(meta: DoctypeMeta): ColumnSelection[] {\n\tconst links = new Map<string, LinkDeclaration>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinks.set(link.fieldname ?? key, link)\n\t\t}\n\t}\n\treturn collectColumns(meta.fields, links)\n}\n\n/**\n * Resolve the declared field this doctype's records are looked up by.\n *\n * Delegates the *rule* to `@stonecrop/schema` so the server's SQL identity predicate and the\n * client's record keying name the same field — including the `id` fallback, whose absence here\n * used to make the two disagree: a doctype declaring no `primaryKey` was keyed by `id` on the\n * client and refused outright by this adapter, so every fetch answered `null` and looked exactly\n * like a record that does not exist.\n *\n * Returns `undefined` only when the resolved name is not a declared field — a doctype with no\n * `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields\n * only, so the row map would key on a column the SELECT never returned and every lookup would miss\n * silently. Callers must say so rather than answer `null`.\n *\n * Descends into fieldsets, because both halves of the question already do — `getColumnSelections` selects\n * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this\n * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose\n * SELECT carried its own key column had no identity to look that column up by.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\tconst fieldname = getRecordIdField(meta.fields)\n\treturn flattenFields(meta.fields).find((f): f is ValueField => f.kind === 'field' && f.fieldname === fieldname)\n}\n\n/**\n * Assert that every registered action handler names a doctype and an action that exist.\n *\n * An unregistered action is fine — a transition needs no effect. The reverse is not: a handler\n * registered under a key nothing resolves to can never run, and **nothing says so at dispatch**.\n * `applyGuardedTransition` fails loudly only when the action also has no state outcome; when it\n * has one, the missing effect is skipped and the state write still reports success. So renaming a\n * doctype leaves `approve` moving records to APPROVED while its ledger posting quietly stops.\n *\n * Two ways a key fails to resolve, and the second is the trap. `getMeta` falls back to matching a\n * slug, but dispatch looks handlers up by `meta.name`, so a slug-keyed registration resolves to a\n * real doctype here and still never fires. It is reported as its own case rather than as \"unknown\n * doctype\", because the repair is different.\n *\n * Throws rather than warns: there is no legitimate reason to register a handler for an action that\n * does not exist, and the alternative is a silent half-executed workflow. Every offender is\n * collected so a consumer with several fixes them in one pass.\n */\nfunction assertActionHandlersResolve(actionHandlers: Record<string, Record<string, ActionHandler>>): void {\n\t// Nothing registered, nothing to check.\n\tconst registered = Object.entries(actionHandlers)\n\tif (registered.length === 0) return\n\n\t// An empty registry cannot tell \"this key is stale\" from \"doctypes have not loaded yet\" — a\n\t// host is free to build the schema before its loader runs. Warn on that ambiguity rather than\n\t// failing a boot that is merely early.\n\tif (getAllMeta().length === 0) {\n\t\t// oxlint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'[@stonecrop/graphql-middleware] Schema built with no doctypes registered, so the ' +\n\t\t\t\t'`actionHandlers` map could not be verified. Load doctypes before building the schema to ' +\n\t\t\t\t'have stale handler keys reported.'\n\t\t)\n\t\treturn\n\t}\n\n\tconst orphans: string[] = []\n\tfor (const [doctypeKey, handlers] of registered) {\n\t\tconst meta = getMeta(doctypeKey)\n\t\tif (!meta) {\n\t\t\torphans.push(`\"${doctypeKey}\": no doctype by that name is registered`)\n\t\t\tcontinue\n\t\t}\n\t\tif (meta.name !== doctypeKey) {\n\t\t\torphans.push(\n\t\t\t\t`\"${doctypeKey}\": matches the doctype named \"${meta.name}\" by slug, but handlers are looked up by name — key it \"${meta.name}\"`\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst actions = meta.workflow?.actions ?? {}\n\t\tfor (const actionKey of Object.keys(handlers)) {\n\t\t\tif (!(actionKey in actions)) {\n\t\t\t\torphans.push(`\"${doctypeKey}.${actionKey}\": the doctype declares no action by that key`)\n\t\t\t}\n\t\t}\n\t}\n\n\tif (orphans.length > 0) {\n\t\tthrow new Error(\n\t\t\t`StonecropPlugin: ${orphans.length} registered action handler${orphans.length === 1 ? '' : 's'} ` +\n\t\t\t\t`cannot be reached and would never run:\\n ${orphans.join('\\n ')}`\n\t\t)\n\t}\n}\n\n/**\n * Refuse a doctype set whose links or `inherits` name a doctype nobody registered.\n *\n * What it prevents is silent: the link read does `const targetMeta = getMeta(link.target)` followed\n * by `if (!targetMeta) continue`, so an unresolvable target drops the relation from the response\n * with no error. On the wire that is indistinguishable from \"this record has no such relation\", and\n * a typo in a target reads as a legitimately empty link forever.\n *\n * Throws rather than warns, like the handler check above: a link pointing at a doctype that does not\n * exist has no correct reading. Every offender is collected so a consumer fixes them in one pass.\n *\n * Deliberately no empty-registry warning, unlike `assertActionHandlersResolve`. That one warns\n * because a registered handler map is evidence the host meant to be checked; here there is no such\n * evidence, so warning would fire on every host that loads doctypes after building its schema —\n * and an advisory that fires on a correct setup is worse than none. An empty registry simply\n * reports nothing, because the loop has nothing to walk.\n */\nfunction assertReferencesResolve(): void {\n\tconst broken = validateReferences()\n\tif (broken.length === 0) return\n\n\tthrow new Error(\n\t\t`StonecropPlugin: ${broken.length} doctype reference${broken.length === 1 ? '' : 's'} ` +\n\t\t\t`cannot be resolved and would silently drop the relation:\\n ` +\n\t\t\tbroken.map(e => `${e.path.join('.')}: ${e.message}`).join('\\n ')\n\t)\n}\n\n/**\n * The error a caller raises when `getPkMeta` cannot resolve an identity field, naming the doctype\n * and both repairs. Shared so the three lookup sites report one diagnosis.\n */\nfunction unresolvableIdentityError(doctype: string): Error {\n\treturn new Error(\n\t\t`Doctype \"${doctype}\" has no identity field: it declares no field with \\`primaryKey: true\\` ` +\n\t\t\t`and no field named \\`id\\`. Declare one of the two — records cannot be fetched or acted on until then.`\n\t)\n}\n\n/**\n * Resolve the PostgreSQL FROM clause target for a doctype.\n * Uses the `tables` override map first; falls back to camelToSnake(name).\n * Schema-qualified names (e.g. \"orpin.plan\") are emitted as \"schema\".\"table\".\n * Values must be bare identifiers or schema.table pairs — not SQL fragments.\n */\n","import { wrapPlans } from 'postgraphile/utils'\n\n/**\n * Options for the Stonecrop debug plugin.\n * @public\n */\nexport interface DebugPluginOptions {\n\t/** Log a message when a plan is built for a Stonecrop field. Default: `true` */\n\tlogPlans?: boolean\n\t/** Log timing for plan construction. Default: `false` */\n\tlogTiming?: boolean\n}\n\n/**\n * Creates a PostGraphile plugin that wraps Stonecrop resolver plans with\n * debug logging. Use it in your preset file:\n *\n * ```typescript\n * import { createStonecropPlugin, createDebugPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * plugins: [createStonecropPlugin(), createDebugPlugin()],\n * }\n * ```\n *\n * Place `createDebugPlugin()` **after** `createStonecropPlugin()` in the\n * plugins array so the wrapper sees the Stonecrop fields.\n *\n * @param options - Optional logging configuration\n * @returns A PostGraphile plugin\n * @public\n */\nexport const createDebugPlugin = (options: DebugPluginOptions = {}): GraphileConfig.Plugin => {\n\tconst { logPlans = true, logTiming = false } = options\n\n\tconst wrapField = (typeName: string, fieldName: string) => ({\n\t\tplan: (plan: () => any) => {\n\t\t\tif (logPlans) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(`[@stonecrop/graphql-middleware] Building plan for ${typeName}.${fieldName}`)\n\t\t\t}\n\n\t\t\tconst start = logTiming ? Date.now() : 0\n\t\t\tconst $result = plan()\n\n\t\t\tif (logTiming) {\n\t\t\t\t// oxlint-disable-next-line no-console\n\t\t\t\tconsole.log(\n\t\t\t\t\t`[@stonecrop/graphql-middleware] Plan built for ${typeName}.${fieldName} in ${Date.now() - start}ms`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn $result\n\t\t},\n\t})\n\n\treturn wrapPlans({\n\t\tQuery: {\n\t\t\tstonecropRecord: wrapField('Query', 'stonecropRecord'),\n\t\t\tstonecropRecords: wrapField('Query', 'stonecropRecords'),\n\t\t\tstonecropMeta: wrapField('Query', 'stonecropMeta'),\n\t\t\tstonecropAllMeta: wrapField('Query', 'stonecropAllMeta'),\n\t\t},\n\t\tMutation: {\n\t\t\tstonecropAction: wrapField('Mutation', 'stonecropAction'),\n\t\t},\n\t})\n}\n","import { PostGraphileAmberPreset } from 'postgraphile/presets/amber'\n\n/**\n * Controls how PostgreSQL column names are mapped to GraphQL field names in the synthesized preset.\n *\n * - `'camel'` (default): `my_column` → `myColumn`. This matches PostGraphile Amber's built-in behaviour.\n *\n * - `'pascal'`: `my_column` → `MyColumn`. Opt in via `createStonecropPreset({ fieldCasing: 'pascal' })` or\n * `grafserv.fieldCasing: 'pascal'` in `nuxt.config.ts`.\n *\n * Smart tag overrides (`@name` on column comments) are respected regardless of this setting.\n * @public\n */\nexport type FieldCasing = 'camel' | 'pascal'\n\n/**\n * Stops Amber taking `id` for Relay's global object identifier.\n *\n * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called\n * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware\n * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`\n * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not\n * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that\n * node id and every read of it then fails on a missing column.\n *\n * Both inflectors must move together. Undoing the rename alone collides with the Relay field still\n * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called\n * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier\n * to `nodeId` keeps Relay working and is the name the schema converter already skips.\n *\n * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.\n */\nconst StonecropNaturalIdPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNaturalIdPlugin',\n\tversion: '0.0.0',\n\tafter: ['PgAttributesPlugin'],\n\tinflection: {\n\t\treplace: {\n\t\t\t// Move Relay's global identifier off `id`...\n\t\t\tnodeIdFieldName() {\n\t\t\t\treturn 'nodeId'\n\t\t\t},\n\n\t\t\t// ...so the real column can keep its own name.\n\t\t\t_attributeName(previous, options, details) {\n\t\t\t\t// `previous` is optional in the inflector signature because a replacement may be the first\n\t\t\t\t// implementation. It never is here — `after: ['PgAttributesPlugin']` guarantees Amber's runs\n\t\t\t\t// first — but the raw attribute name is the correct identity fallback.\n\t\t\t\tconst name = previous?.(details) ?? details.attributeName\n\t\t\t\tif (!details.skipRowId && name === 'row_id') {\n\t\t\t\t\tconst { codec, attributeName } = details\n\t\t\t\t\tconst baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName\n\t\t\t\t\tif (typeof baseName === 'string' && baseName.toLowerCase() === 'id' && !codec.isAnonymous) {\n\t\t\t\t\t\treturn 'id'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn name\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Exposes the many side of a foreign key the database declares as owning.\n *\n * PostGraphile registers both directions of every foreign key, but Amber gives the many side no\n * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s\n * inferred behavior is `[\"resource:select\", behavior]` and nothing more. So a parent type carries\n * no field for its children, and a doctype generated from that schema can never contain a child\n * table. Every one a consumer has is hand-authored.\n *\n * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.\n * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`\n * does not: an order references a party that outlives it. The two are otherwise the same shape, so\n * no amount of reading the relation itself can separate them — and turning the many side on for\n * *every* foreign key would make each referenced table look like somebody's child.\n *\n * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw\n * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.\n *\n * Connection only, deliberately. The converter recognises a Connection type through\n * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`\n * would add a second field per relation that generation then drops on the floor.\n *\n * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the\n * global default and take precedence, so `+manyRelation:resource:connection` there is overridden\n * for every relation — verified, it changes nothing, while `-connection +list` through the same\n * option visibly rewrites the Query fields.\n */\nconst StonecropOwnedRelationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropOwnedRelationsPlugin',\n\tversion: '0.0.0',\n\tgather: {\n\t\thooks: {\n\t\t\tpgRelations_relation(_info, event) {\n\t\t\t\tconst { relation, pgConstraint } = event\n\t\t\t\t// The hook fires once per direction of each constraint; only the backwards one has a\n\t\t\t\t// many side to expose. `confdeltype` is Postgres' own code: 'c' is CASCADE.\n\t\t\t\tif (!relation.isReferencee) return\n\t\t\t\tif (pgConstraint.confdeltype !== 'c') return\n\n\t\t\t\trelation.extensions ??= {}\n\t\t\t\trelation.extensions.tags ??= {}\n\t\t\t\trelation.extensions.tags.behavior = '+manyRelation:resource:connection'\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Offers no database function as a mutation.\n *\n * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard\n * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds\n * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.\n */\nconst StonecropNoFunctionMutationsPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropNoFunctionMutationsPlugin',\n\tversion: '0.0.0',\n\tschema: {\n\t\tentityBehavior: {\n\t\t\tpgResource: {\n\t\t\t\toverride: {\n\t\t\t\t\t// After the hook that applies smart tags, so an app's `@behavior +mutationField` cannot undo it.\n\t\t\t\t\tafter: ['PgBasicsPlugin'],\n\t\t\t\t\tcallback(behavior) {\n\t\t\t\t\t\treturn [behavior, '-mutationField']\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n}\n\nconst StonecropFieldCasingPlugin: GraphileConfig.Plugin = {\n\tname: 'StonecropFieldCasingPlugin',\n\tversion: '0.0.0',\n\tinflection: {\n\t\treplace: {\n\t\t\tattribute(previous, options, details) {\n\t\t\t\treturn this.upperCamelCase(this._attributeName(details))\n\t\t\t},\n\t\t},\n\t},\n}\n\n/**\n * Creates a Stonecrop-flavoured PostGraphile preset.\n *\n * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's\n * recommended defaults. It turns off the mutations Amber generates, a create, update and delete for\n * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write\n * the API offers. Pass it to `extends` in your PostGraphile configuration:\n *\n * ```typescript\n * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [createStonecropPreset()],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL, schemas: ['public'] })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n *\n * @param options - Optional configuration. Pass `{ fieldCasing: 'pascal' }` to enable\n * `MyColumn`-style field names instead of the default `myColumn` (camelCase).\n * @public\n */\nexport const createStonecropPreset = (options?: { fieldCasing?: FieldCasing }): GraphileConfig.Preset => ({\n\textends: [PostGraphileAmberPreset],\n\tplugins: [\n\t\tStonecropNaturalIdPlugin,\n\t\tStonecropOwnedRelationsPlugin,\n\t\tStonecropNoFunctionMutationsPlugin,\n\t\t...(options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : []),\n\t],\n\t// Every write is an action, through `stonecropAction`, and Amber's create, update and delete for\n\t// each table would write past the doctype's guard. Disabled rather than set in\n\t// `schema.defaultBehavior`, which an app's own `defaultBehavior` replaces whole; `disablePlugins`\n\t// lists merge.\n\tdisablePlugins: ['PgMutationCreatePlugin', 'PgMutationUpdateDeletePlugin'],\n})\n\n/**\n * The default Stonecrop PostGraphile preset with camelCase field names.\n *\n * Equivalent to `createStonecropPreset()` with no options. Use this when you\n * do not need to customise field casing:\n *\n * ```typescript\n * import { StonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'\n *\n * export default {\n * extends: [StonecropPreset],\n * pgServices: [makePgService({ connectionString: process.env.DATABASE_URL })],\n * plugins: [createStonecropPlugin()],\n * }\n * ```\n * @public\n */\nexport const StonecropPreset: GraphileConfig.Preset = createStonecropPreset()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,mBAAmB,QAA+C;CACjF,OAAO,gBAAc,MAAM,CAAC,CAAC,QAAQ,MAAuB,EAAE,SAAS,WAAW,CAAC,EAAE,QAAQ;AAC9F;;;ACtBA,IAAM,kCAA4C,IAAI,IAAI;;;;;AAM1D,IAAa,yBAAb,cAA4C,MAAM;CAGhC;CAEA;CAJjB,YAEC,MAEA,QACC;EACD,MAAM,gBAAgB,OAAO,KAAI,MAAK,KAAK,EAAE,KAAK,KAAK,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC,KAAK,IAAI;EACtF,MAAM,iCAAiC,KAAK,KAA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AyC,sBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stonecrop/graphql-middleware",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.48.0",
|
|
4
4
|
"description": "GraphQL middleware for PostGraphile and Stonecrop schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"graphql",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"graphql": "^16.14.0",
|
|
42
42
|
"postgraphile": "^5.0.3",
|
|
43
43
|
"temporal-polyfill": "^1.0.5",
|
|
44
|
-
"@stonecrop/schema": "0.
|
|
44
|
+
"@stonecrop/schema": "0.48.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@electric-sql/pglite": "^0.5.8",
|