@stonecrop/graphql-middleware 0.16.5 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["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\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 cross-doctype references (Link fields, inherits, etc.)\n * Call after all doctypes are loaded.\n * @public\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 && !doctypeRegistry.has(doctype.inherits)) {\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\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.kind !== 'field') continue\n\t\t\tconst target = field.doctype\n\t\t\tif (target !== undefined && !doctypeRegistry.has(target)) {\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\tfor (const [key, link] of Object.entries(doctype.links)) {\n\t\t\t\tif (!doctypeRegistry.has(link.target)) {\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\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 two closures change per backend.\n * @public\n */\nexport interface GuardedTransitionIO {\n\t/** Read the record's current workflow state (the value of its `status` field), or undefined if unknown. */\n\treadState: () => Promise<string | undefined>\n\t/** Persist the record's new workflow state, written verbatim. */\n\twriteState: (nextState: string) => Promise<void>\n\t/**\n\t * Persist record field data for a mutate-in-place self-transition, returning the full updated\n\t * record (so the client writeback reflects the new data). Optional: a backend with no data-write\n\t * path (e.g. PostGraphile today, which writes only `status`) omits it, and a self-transition is\n\t * then rejected loudly rather than silently dropped.\n\t */\n\twriteData?: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>\n}\n\n/**\n * Apply a workflow action's state transition 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 writes `nextState`\n * verbatim. Storage access is injected via `io` so this one guard serves every backend\n * and can never disagree with the frontend's `getAvailableTransitions`, which shares the\n * same predicate.\n *\n * There are three action shapes this guard distinguishes:\n * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\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 * A backend without a data-write path rejects it loudly instead of dropping it silently.\n * - Anything else with no `nextState` and no `selfTransition` flag is a genuine authoring mistake (or a\n * stateless side-effect command whose server handler is not wired — the intended `callHandler` primitive\n * is still unimplemented): it fails loudly before touching 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\n * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)\n * @returns Action result envelope — the resulting `data.state` for a transition, the full record for a self-transition\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\t// A non-self action with no target has nothing to apply — fail loudly WITHOUT touching the backend\n\t// (a stateless command's server handler is not wired; a genuine bug should not read/write anything).\n\tif (!actionDef.selfTransition && actionDef.nextState == null) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tdata: null,\n\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" has no workflow transition and no server-side effect is wired — nothing was executed.`,\n\t\t}\n\t}\n\n\tconst currentState = (await io.readState()) ?? ''\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// Self-transition: mutate record data in place, keep the current state. Requires a backend data-write\n\t// capability; without it (e.g. PostGraphile today) reject loudly. The full updated record is returned\n\t// so the client writeback reflects the new data.\n\tif (actionDef.selfTransition) {\n\t\tif (!io.writeData) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdata: null,\n\t\t\t\terror: `Action \"${actionDef.label ?? 'unknown'}\" persists record data in place, which this backend does not support.`,\n\t\t\t}\n\t\t}\n\t\tconst record = await io.writeData(data ?? {})\n\t\treturn { success: true, data: record, 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. Two concurrent transitions on the same record can both pass\n\t// the guard before either writes, so both \"succeed\" even when the workflow intended\n\t// them to be mutually exclusive. Closing this requires guarding and writing in one\n\t// statement — an atomic `UPDATE ... SET status = nextState WHERE status = ANY(allowedStates)`\n\t// — and reporting \"no rows updated\" as a rejected transition. Deferred for now.\n\tif (actionDef.nextState == null) {\n\t\t// Unreachable (guarded above), but keeps `nextState` narrowed to a string below.\n\t\treturn { success: false, data: null, error: 'nothing was executed' }\n\t}\n\tawait io.writeState(actionDef.nextState)\n\n\treturn {\n\t\tsuccess: true,\n\t\tdata: { state: actionDef.nextState },\n\t\terror: null,\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\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}\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\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}\n\n\ttype StonecropRecordsResult {\n\t\tdata: [JSON!]!\n\t\tdoctype: String!\n\t\tcount: Int!\n\t}\n\n\ttype StonecropActionResult {\n\t\tsuccess: Boolean!\n\t\tdata: JSON\n\t\terror: 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\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 {\n\tDoctypeField,\n\tDoctypeMeta,\n\tLinkDeclaration,\n\tTableField,\n\tValueField,\n\tGetRecordOptions,\n} from '@stonecrop/schema'\nimport { camelToSnake, getPrimaryKeyField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport { applyGuardedTransition } from '../dispatch/transition'\nimport { typeDefs } from '../typeDefs'\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 `camelToSnake(doctype.name)`.\n\t */\n\ttables?: Record<string, string>\n}\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\treturn 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 pgExecutors = (build as any).input?.pgRegistry?.pgExecutors as Record<string, PgExecutor> | undefined\n\t\tconst executor = pgExecutors ? Object.values(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\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\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\t\t\t\t\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\t\t\t\t\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\t\t\t\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\t\t\t\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\t\t\t\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst results: Array<{\n\t\t\t\t\t\t\t\t\t\tdata: Record<string, unknown> | null\n\t\t\t\t\t\t\t\t\t\tdoctype: string\n\t\t\t\t\t\t\t\t\t\tunknownLinks?: string[]\n\t\t\t\t\t\t\t\t\t}> = Array.from({ length: specs.length })\n\n\t\t\t\t\t\t\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\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) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t\t\t\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t\t\t\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\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\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\t\t\t\t\t\t\tvalues: [ids],\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\t\t\t\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t\t\t\t\t\t\tfor (const i of indices) {\n\t\t\t\t\t\t\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\t\t\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\t\t\t\t\t\t\tif (!row) {\n\t\t\t\t\t\t\t\t\t\t\t\tresults[i] = { data: null, doctype }\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\n\t\t\t\t\t\t\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\t\t\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\t\t\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\t\t\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t? new Set(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t: null\n\n\t\t\t\t\t\t\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\t\t\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst shouldInclude =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tincludeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\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\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\t\t\t\t\t\t\trowData[linkName] = await handler(pgClient, rowData, link)\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\tcontinue\n\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\tif (effectiveMethod !== 'sync' && !includeSet?.has(linkName)) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetColumns = getSqlColumns(targetMeta)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\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\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit)\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// 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\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\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: linkValues,\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\trowData[linkName] = linked\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.fieldname) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst fkValue = rowData[link.fieldname]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\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\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetPkMeta) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\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\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\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [fkValue],\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\trowData[linkName] = linked[0] ?? null\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\n\t\t\t\t\t\t\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\t\t\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\t\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\t\t\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\t\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\t\t\t\t\t\t}\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\treturn results\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\n\t\t\t\t\t\tstonecropRecords(_: any, { $doctype, $filters, $orderBy, $limit, $offset }: 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}),\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\treturn { data: [], doctype, count: 0 }\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 columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection)\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\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(`\"${camelToSnake(field)}\" = $${values.length}`)\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\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// LIMIT / OFFSET\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 (spec.limit != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tvalues.push(spec.limit)\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 ${columns} FROM ${resolveTableName(meta.name, options.tables)}${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\n\t\t\t\t\t\t\t\t\t\t\t// Total count matching filters (independent of LIMIT/OFFSET)\n\t\t\t\t\t\t\t\t\t\t\tlet count = rows.length\n\t\t\t\t\t\t\t\t\t\t\tif (spec.limit != null || spec.offset != null) {\n\t\t\t\t\t\t\t\t\t\t\t\tconst countValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhere: string[] = []\n\t\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\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\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\t\tif (!knownFields.has(field)) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountWhere.push(`\"${camelToSnake(field)}\" = $${countValues.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\tconst countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : ''\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)}${countWhereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: countValues,\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: rows, doctype, 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 pkMeta = getPkMeta(meta)\n\t\t\t\t\t\t\t\t\tif (!pkMeta) {\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: `No primary key for 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\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\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// 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 argList = (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}>\n\t\t\t\t\t\t\t\t\tconst recordId = argList[0]?.id\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\treturn await applyGuardedTransition(actionDef, {\n\t\t\t\t\t\t\t\t\t\t\treadState: async () => {\n\t\t\t\t\t\t\t\t\t\t\t\tif (recordId == null) return undefined\n\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<{ status: string | null }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT \"status\" FROM ${table} WHERE \"${pkColumn}\"::text = $1`,\n\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})\n\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0]?.status == null ? undefined : rows[0].status\n\t\t\t\t\t\t\t\t\t\t\t},\n\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\tawait debugSql(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `UPDATE ${table} SET \"status\" = $1 WHERE \"${pkColumn}\"::text = $2`,\n\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})\n\t\t\t\t\t\t\t\t\t\t\t},\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\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\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).\n */\nfunction flattenFields(fields: DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Derive quoted SQL column entries 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>): string[] {\n\tconst columns: string[] = []\n\tfor (const f of flattenFields(fields)) {\n\t\tif (f.kind !== 'field') continue\n\t\t// A computed field has no backing DB column.\n\t\tif (f.computed) continue\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// shared rule, also used by the client resolver; 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\tconst col = camelToSnake(f.fieldname)\n\t\tcolumns.push(col !== f.fieldname ? `\"${col}\" AS \"${f.fieldname}\"` : `\"${f.fieldname}\"`)\n\t}\n\treturn columns\n}\n\n/**\n * Derive a quoted SQL column list from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, then\n * aliases it back to the fieldname 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 getSqlColumns(meta: DoctypeMeta): string {\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).join(', ')\n}\n\n/**\n * Find the field marked `primaryKey` in the doctype.\n * Returns undefined when none is marked (PK-less doctypes).\n *\n * Delegates to `@stonecrop/schema` so the server's identity predicate and the client's record\n * keying resolve the same field — this used to be a private re-implementation of that rule.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\treturn getPrimaryKeyField(meta.fields)\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 */\nfunction resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn `\"${target.slice(0, dotIndex)}\".\"${target.slice(dotIndex + 1)}\"`\n\t}\n\treturn `\"${target}\"`\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 * - `'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\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. 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: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],\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"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","direct","getAllMeta","hasMeta","clearRegistry","validateReferences","field","target","key","link","registry","registerFetchHandler","handler","getFetchHandler","clearFetchHandlers","applyGuardedTransition","actionDef","io","currentState","isActionAllowedInState","typeDefs","gql","createStonecropPlugin","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","i","d","results","indices","meta","pkMeta","getPkMeta","pkColumn","camelToSnake","columns","getSqlColumns","ids","rows","resolveTableName","rowByPk","r","specId","row","rowData","recordOptions","includeAll","includeSet","linkName","fetch","isMany","effectiveMethod","effectiveLimit","handlerName","targetMeta","targetColumns","backlinkCol","sql","linkValues","linked","fkValue","targetPkMeta","targetPkColumn","unknownLinks","$filters","$orderBy","$limit","$offset","spec","knownFields","flattenFields","f","values","whereClauses","value","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","table","recordId","nextState","fields","collectColumns","links","resolveLinkRenderMode","col","getPrimaryKeyField","tables","pascalToSnake","dotIndex","createDebugPlugin","logPlans","logTiming","wrapField","typeName","plan","start","$result","wrapPlans","StonecropFieldCasingPlugin","previous","details","createStonecropPreset","PostGraphileAmberPreset","StonecropPreset"],"mappings":";;;;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AAAA,EAPiB;AAAA,EAEA;AAMlB;AAmBO,SAASG,GAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,GAAYH,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,OAAoE;AAAA,EACzG,SAAS,CAACsJ,EAAuB;AAAA,EACjC,SAAStJ,GAAS,gBAAgB,WAAW,CAACkJ,EAA0B,IAAI,CAAA;AAC7E,IAmBaK,KAAyCF,GAAA;"}
1
+ {"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/fetchHandlers.ts","../src/dispatch/transition.ts","../src/typeDefs.ts","../src/plugin/postgraphile.ts","../src/debug.ts","../src/preset.ts"],"sourcesContent":["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\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 cross-doctype references (link targets, `inherits`) against what 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 * 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\t// Check link field targets — `doctype` is both the link marker and its target.\n\t\tfor (const field of doctype.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\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\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:\n\t * - a string — the record's current state\n\t * - `undefined` — the record exists but carries no workflow state\n\t * - `null` — **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 (so the client writeback reflects it).\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 * Returning a full record makes it the client writeback payload; returning `undefined` leaves\n\t * the doctype's own outcome to decide what comes back.\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 * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.\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 * - 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 * - 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 the client writeback reflects the new data. 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 { 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\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}\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\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}\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\tdata: JSON\n\t\terror: 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 {\n\tDoctypeField,\n\tDoctypeMeta,\n\tLinkDeclaration,\n\tTableField,\n\tValueField,\n\tGetRecordOptions,\n} from '@stonecrop/schema'\nimport { camelToSnake, getRecordIdField, pascalToSnake, resolveLinkRenderMode } from '@stonecrop/schema'\nimport { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg'\nimport type { PgClient, PgExecutor } from '@dataplan/pg'\nimport { constant, lambda, object } from 'postgraphile/grafast'\nimport { GraphileConfig } from 'postgraphile/graphile-build'\nimport { extendSchema } from 'postgraphile/utils'\n\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. Returning the updated record makes it the\n * client writeback payload; returning `undefined` leaves the doctype's own outcome to decide.\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 `camelToSnake(doctype.name)`.\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 to `stonecropRecords` when the caller requests no `limit`. Defaults 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 * `hasMore` reports whether the cap truncated the result, so a capped page is always\n\t * distinguishable from a complete one without asking for a count.\n\t *\n\t * Set to `null` for no default cap. That is the pre-0.17 behaviour and it means an unqualified\n\t * list query returns the whole table.\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/**\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\treturn 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 pgExecutors = (build as any).input?.pgRegistry?.pgExecutors as Record<string, PgExecutor> | undefined\n\t\tconst executor = pgExecutors ? Object.values(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\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\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\tasync (pgClient: PgClient, specs) => {\n\t\t\t\t\t\t\t\t\t// Group specs by doctype to batch the main SELECT per table\n\t\t\t\t\t\t\t\t\tconst byDoctype = new Map<string, number[]>()\n\t\t\t\t\t\t\t\t\tfor (let i = 0; i < specs.length; i++) {\n\t\t\t\t\t\t\t\t\t\tconst d = String(specs[i].doctype)\n\t\t\t\t\t\t\t\t\t\tif (!byDoctype.has(d)) byDoctype.set(d, [])\n\t\t\t\t\t\t\t\t\t\tbyDoctype.get(d)!.push(i)\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst results: Array<{\n\t\t\t\t\t\t\t\t\t\tdata: Record<string, unknown> | null\n\t\t\t\t\t\t\t\t\t\tdoctype: string\n\t\t\t\t\t\t\t\t\t\tunknownLinks?: string[]\n\t\t\t\t\t\t\t\t\t}> = Array.from({ length: specs.length })\n\n\t\t\t\t\t\t\t\t\tfor (const [doctype, indices] of byDoctype) {\n\t\t\t\t\t\t\t\t\t\tconst meta = getMeta(doctype)\n\t\t\t\t\t\t\t\t\t\tif (!meta) {\n\t\t\t\t\t\t\t\t\t\t\tfor (const i of indices) results[i] = { data: null, doctype }\n\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\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\t\t\t\t\t\t// doctype nobody can look up is a misconfiguration, not an empty result.\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(doctype)\n\t\t\t\t\t\t\t\t\t\tconst pkColumn = camelToSnake(pkMeta.fieldname)\n\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\tconst ids = indices.map(i => String(specs[i].id))\n\n\t\t\t\t\t\t\t\t\t\t// TODO(perf): queries per doctype group could be parallelized with Promise.all across doctype groups;\n\t\t\t\t\t\t\t\t\t\t// requires refactoring the grouped-by-doctype loop to collect promises before resolving results\n\t\t\t\t\t\t\t\t\t\t// oxlint-disable-next-line eslint/no-await-in-loop -- sequential per-doctype SQL; see TODO above\n\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\ttext: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE \"${pkColumn}\"::text = ANY($1::text[])`,\n\t\t\t\t\t\t\t\t\t\t\tvalues: [ids],\n\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\t\t\t// Use String() so integer PKs (e.g. serial) match the string ids from GraphQL\n\t\t\t\t\t\t\t\t\t\tconst rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]))\n\n\t\t\t\t\t\t\t\t\t\t// A declared key the database does not actually enforce as unique collapses several\n\t\t\t\t\t\t\t\t\t\t// rows into that Map, and it keeps whichever came last — one arbitrary record,\n\t\t\t\t\t\t\t\t\t\t// returned as though it were *the* record, with nothing to say so. Refuse instead.\n\t\t\t\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t\t\t\t// This is exact rather than a proxy for the problem: `ANY` matches each requested id\n\t\t\t\t\t\t\t\t\t\t// once, so a shortfall here means two distinct rows genuinely share a key value. A\n\t\t\t\t\t\t\t\t\t\t// `pg_index` check would instead ask whether a unique constraint exists, which is the\n\t\t\t\t\t\t\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\t\t\t\t\t\t// unconstrained, which is a real and common shape.\n\t\t\t\t\t\t\t\t\t\tif (rows.length !== rowByPk.size) {\n\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`Doctype \"${doctype}\" declares \"${pkMeta.fieldname}\" as its identity, but that column ` +\n\t\t\t\t\t\t\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\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\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\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tfor (const i of indices) {\n\t\t\t\t\t\t\t\t\t\t\tconst specId = String(specs[i].id)\n\t\t\t\t\t\t\t\t\t\t\tconst row = rowByPk.get(specId)\n\n\t\t\t\t\t\t\t\t\t\t\tif (!row) {\n\t\t\t\t\t\t\t\t\t\t\t\tresults[i] = { data: null, doctype }\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\n\t\t\t\t\t\t\t\t\t\t\tconst rowData: Record<string, unknown> = { ...row }\n\t\t\t\t\t\t\t\t\t\t\tconst recordOptions = (specs[i].options ?? {}) as GetRecordOptions\n\t\t\t\t\t\t\t\t\t\t\tconst includeAll = recordOptions.includeNested === true\n\t\t\t\t\t\t\t\t\t\t\tconst includeSet = Array.isArray(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t? new Set(recordOptions.includeNested)\n\t\t\t\t\t\t\t\t\t\t\t\t: null\n\n\t\t\t\t\t\t\t\t\t\t\t// FetchStrategy dispatch over link declarations\n\t\t\t\t\t\t\t\t\t\t\tif (meta.links) {\n\t\t\t\t\t\t\t\t\t\t\t\tfor (const [linkName, link] of Object.entries(meta.links)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst fetch = link.fetch\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy')\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst shouldInclude =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tincludeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync')\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!shouldInclude) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (effectiveMethod === 'custom' && fetch?.method === 'custom') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = fetch.handler\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handler = getFetchHandler(handlerName)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (handler) {\n\t\t\t\t\t\t\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\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\t\t\t\t\t\t\trowData[linkName] = await handler(pgClient, rowData, link)\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\tcontinue\n\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\tif (effectiveMethod !== 'sync' && !includeSet?.has(linkName)) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetMeta = getMeta(link.target)\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetMeta) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetColumns = getSqlColumns(targetMeta)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (isMany) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.backlink) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst backlinkCol = camelToSnake(link.backlink)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlet sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${backlinkCol}\"::text = $1`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst linkValues: unknown[] = [specId]\n\t\t\t\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\t\t\tsql += ` LIMIT $2`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlinkValues.push(effectiveLimit)\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// 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\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\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: sql,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: linkValues,\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\trowData[linkName] = linked\n\t\t\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!link.fieldname) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst fkValue = rowData[link.fieldname]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (fkValue == null) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trowData[linkName] = null\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\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// `continue` here would drop the link from the payload, which reads to the\n\t\t\t\t\t\t\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\t\t\t\t\t\t// cannot be identified\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkMeta = getPkMeta(targetMeta)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetPkColumn = camelToSnake(targetPkMeta.fieldname)\n\t\t\t\t\t\t\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\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\t\t\t\t\t\t\tconst { rows: linked } = await debugSql<Record<string, unknown>>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE \"${targetPkColumn}\" = $1`,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: [fkValue],\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\trowData[linkName] = linked[0] ?? null\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\n\t\t\t\t\t\t\t\t\t\t\t// Names in includeNested that don't correspond to any link\n\t\t\t\t\t\t\t\t\t\t\tconst unknownLinks =\n\t\t\t\t\t\t\t\t\t\t\t\tincludeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links!)) : undefined\n\n\t\t\t\t\t\t\t\t\t\t\tresults[i] = {\n\t\t\t\t\t\t\t\t\t\t\t\tdata: rowData,\n\t\t\t\t\t\t\t\t\t\t\t\tdoctype,\n\t\t\t\t\t\t\t\t\t\t\t\tunknownLinks: unknownLinks?.length ? unknownLinks : undefined,\n\t\t\t\t\t\t\t\t\t\t\t}\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\treturn results\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\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 columns = getSqlColumns(meta)\n\t\t\t\t\t\t\t\t\t\t\tconst values: unknown[] = []\n\n\t\t\t\t\t\t\t\t\t\t\t// WHERE from filters (parameterised — safe against SQL injection)\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\tvalues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\twhereClauses.push(`\"${camelToSnake(field)}\" = $${values.length}`)\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\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// 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 =\n\t\t\t\t\t\t\t\t\t\t\t\tspec.limit ?? (options.defaultRecordLimit === undefined ? 200 : options.defaultRecordLimit)\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 ${columns} FROM ${resolveTableName(meta.name, options.tables)}${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\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\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 countValues: unknown[] = []\n\t\t\t\t\t\t\t\t\t\t\t\tconst countWhere: string[] = []\n\t\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\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\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\t\tif (!knownFields.has(field)) continue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountValues.push(value)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcountWhere.push(`\"${camelToSnake(field)}\" = $${countValues.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\tconst countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : ''\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)}${countWhereClause}`,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalues: countValues,\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 argList = (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\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// 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(actionDef, {\n\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// 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// the same answer as a lookup that misses: `null`, not `undefined`.\n\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// 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// 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// 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// race: two concurrent approvals both read PENDING and both proceed.\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst { rows } = await debugSql<{ status: string | null }>(tx, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT \"status\" FROM ${table} WHERE \"${pkColumn()}\"::text = $1 FOR UPDATE`,\n\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})\n\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\tif (rows.length === 0) return null\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn rows[0].status ?? 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\twriteState: async (nextState: string) => {\n\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\ttext: `UPDATE ${table} SET \"status\" = $1 WHERE \"${pkColumn()}\"::text = $2`,\n\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})\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\trunEffect: handler\n\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\thandler({\n\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\tdoctype: String(spec.doctype),\n\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\tmeta,\n\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\tdata: recordData,\n\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\tcurrentState,\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: undefined,\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\treturn outcome\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\n// ===========================================================================\n// SQL column helpers\n// ===========================================================================\n\n/**\n * Recursively flatten Fieldset containers into a flat array of non-container fields.\n * Fieldset entries are replaced by their children; all other fields pass through.\n * Used by getSqlColumns (for SELECT) and knownFields (for filter/orderBy validation).\n */\nfunction flattenFields(fields: DoctypeField[]): (ValueField | TableField)[] {\n\tconst result: (ValueField | TableField)[] = []\n\tfor (const f of fields) {\n\t\tif (f.kind === 'fieldset') {\n\t\t\tresult.push(...flattenFields(f.schema))\n\t\t} else {\n\t\t\tresult.push(f)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Derive quoted SQL column entries 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>): string[] {\n\tconst columns: string[] = []\n\tfor (const f of flattenFields(fields)) {\n\t\tif (f.kind !== 'field') continue\n\t\t// A computed field has no backing DB column.\n\t\tif (f.computed) continue\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// shared rule, also used by the client resolver; 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\tconst col = camelToSnake(f.fieldname)\n\t\tcolumns.push(col !== f.fieldname ? `\"${col}\" AS \"${f.fieldname}\"` : `\"${f.fieldname}\"`)\n\t}\n\treturn columns\n}\n\n/**\n * Derive a quoted SQL column list from doctype field definitions.\n * Applies camelToSnake to each fieldname to get the DB column name, then\n * aliases it back to the fieldname 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 getSqlColumns(meta: DoctypeMeta): string {\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).join(', ')\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 top-level field — a doctype\n * with no `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared\n * fields only, so the row map would key on a column the SELECT never returned and every lookup\n * would miss silently. Callers must say so rather than answer `null`.\n */\nfunction getPkMeta(meta: DoctypeMeta): ValueField | undefined {\n\tconst fieldname = getRecordIdField(meta.fields)\n\treturn 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 */\nfunction resolveTableName(name: string, tables?: Record<string, string>): string {\n\tconst target = tables?.[name] ?? pascalToSnake(name)\n\tconst dotIndex = target.indexOf('.')\n\tif (dotIndex > 0) {\n\t\treturn `\"${target.slice(0, dotIndex)}\".\"${target.slice(dotIndex + 1)}\"`\n\t}\n\treturn `\"${target}\"`\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 * - `'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\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. 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: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],\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"],"names":["doctypeRegistry","DoctypeValidationError","file","errors","errorMessages","e","loadDoctypes","dir","options","entries","readdirSync","entry","fullPath","join","statSync","loadDoctypeFile","filePath","content","readFileSync","data","err","parseError","result","validateDoctype","doctype","parseDoctype","loadDoctypesFromObject","doctypes","name","withName","getMeta","direct","getAllMeta","hasMeta","clearRegistry","validateReferences","field","target","key","link","registry","registerFetchHandler","handler","getFetchHandler","clearFetchHandlers","applyGuardedTransition","actionDef","io","label","isSelfTransition","hasStateOutcome","isGuarded","currentState","state","created","isActionAllowedInState","effectResult","typeDefs","gql","ActionRolledBack","outcome","createStonecropPlugin","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","assertActionHandlersResolve","assertReferencesResolve","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","i","d","results","indices","meta","pkMeta","getPkMeta","unresolvableIdentityError","pkColumn","camelToSnake","columns","getSqlColumns","ids","rows","resolveTableName","rowByPk","r","specId","row","rowData","recordOptions","includeAll","includeSet","linkName","fetch","isMany","effectiveMethod","effectiveLimit","handlerName","targetMeta","targetColumns","backlinkCol","sql","linkValues","linked","fkValue","targetPkMeta","targetPkColumn","unknownLinks","$filters","$orderBy","$limit","$offset","$includeTotal","spec","knownFields","flattenFields","f","values","whereClauses","value","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","hasMore","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","table","argList","recordId","recordData","tx","nextState","fields","collectColumns","links","resolveLinkRenderMode","col","fieldname","getRecordIdField","actionHandlers","registered","orphans","doctypeKey","handlers","actions","actionKey","broken","tables","pascalToSnake","dotIndex","createDebugPlugin","logPlans","logTiming","wrapField","typeName","plan","start","$result","wrapPlans","StonecropFieldCasingPlugin","previous","details","createStonecropPreset","PostGraphileAmberPreset","StonecropPreset"],"mappings":";;;;;;;;AAMA,MAAMA,wBAAgD,IAAA;AAM/C,MAAMC,UAA+B,MAAM;AAAA,EACjD,YAEiBC,GAEAC,GACf;AACD,UAAMC,IAAgBD,EAAO,IAAI,CAAAE,MAAK,KAAKA,EAAE,KAAK,KAAK,GAAG,CAAC,KAAKA,EAAE,OAAO,EAAE,EAAE,KAAK;AAAA,CAAI;AACtF,UAAM,iCAAiCH,CAAI;AAAA,EAAME,CAAa,EAAE,GALhD,KAAA,OAAAF,GAEA,KAAA,SAAAC,GAIhB,KAAK,OAAO;AAAA,EACb;AAAA,EAPiB;AAAA,EAEA;AAMlB;AAmBO,SAASG,GAAaC,GAAaC,IAA+B,IAAU;AAClF,QAAMC,IAAUC,GAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,GAAKN,GAAKI,CAAK;AAGhC,IAFaG,GAASF,CAAQ,EAErB,gBACRN,GAAaM,GAAUJ,CAAO,IACpBG,EAAM,SAAS,OAAO,KAChCI,GAAgBH,GAAUJ,CAAO;AAAA,EAEnC;AACD;AAKA,SAASO,GAAgBC,GAAkBR,GAAoC;AAC9E,QAAMS,IAAUC,GAAaF,GAAU,OAAO;AAC9C,MAAIG;AAEJ,MAAI;AACH,IAAAA,IAAO,KAAK,MAAMF,CAAO;AAAA,EAC1B,SAASG,GAAK;AACb,UAAMC,IAA8B;AAAA,MACnC,MAAM,CAAA;AAAA,MACN,SAAS,iBAAiBD,aAAe,QAAQA,EAAI,UAAU,OAAOA,CAAG,CAAC;AAAA,IAAA;AAG3E,QAAIZ,EAAQ,iBAAiB;AAC5B,MAAAA,EAAQ,UAAUQ,GAAU,CAACK,CAAU,CAAC;AACxC;AAAA,IACD;AACA,UAAM,IAAIpB,EAAuBe,GAAU,CAACK,CAAU,CAAC;AAAA,EACx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;AAAA,QACP,kDAAkDE,CAAQ,IAAIvC,CAAS,OAAO,KAAK,QAAQyC,CAAK;AAAA,MAAA,GAI3FC;AAAA,IACR;AAAA,EAAA;AAGD,SAAOC,GAAU;AAAA,IAChB,OAAO;AAAA,MACN,iBAAiBL,EAAU,SAAS,iBAAiB;AAAA,MACrD,kBAAkBA,EAAU,SAAS,kBAAkB;AAAA,MACvD,eAAeA,EAAU,SAAS,eAAe;AAAA,MACjD,kBAAkBA,EAAU,SAAS,kBAAkB;AAAA,IAAA;AAAA,IAExD,UAAU;AAAA,MACT,iBAAiBA,EAAU,YAAY,iBAAiB;AAAA,IAAA;AAAA,EACzD,CACA;AACF,GCrDMM,KAAoD;AAAA,EACzD,MAAM;AAAA,EACN,SAAS;AAAA,EACT,YAAY;AAAA,IACX,SAAS;AAAA,MACR,UAAUC,GAAU7K,GAAS8K,GAAS;AACrC,eAAO,KAAK,eAAe,KAAK,eAAeA,CAAO,CAAC;AAAA,MACxD;AAAA,IAAA;AAAA,EACD;AAEF,GAsBaC,KAAwB,CAAC/K,OAAoE;AAAA,EACzG,SAAS,CAACgL,EAAuB;AAAA,EACjC,SAAShL,GAAS,gBAAgB,WAAW,CAAC4K,EAA0B,IAAI,CAAA;AAC7E,IAmBaK,KAAyCF,GAAA;"}
@@ -1,44 +1,97 @@
1
1
  /**
2
2
  * Backend IO the dispatch layer injects so the transition logic stays storage-agnostic.
3
3
  * The same guard runs whether the record lives in Postgres, a mock executor, or an
4
- * in-memory Map — only these two closures change per backend.
4
+ * in-memory Map — only these closures change per backend.
5
5
  * @public
6
6
  */
7
7
  export interface GuardedTransitionIO {
8
- /** Read the record's current workflow state (the value of its `status` field), or undefined if unknown. */
9
- readState: () => Promise<string | undefined>;
8
+ /**
9
+ * Read the record's current workflow state — the value of its `status` field.
10
+ *
11
+ * Three answers, and the difference between the last two matters:
12
+ * - a string — the record's current state
13
+ * - `undefined` — the record exists but carries no workflow state
14
+ * - `null` — **there is no such record**
15
+ *
16
+ * Collapsing those two into `undefined` is what let an action against a missing record report
17
+ * success: the state read as `''`, an action declaring no `allowedStates` passed the guard, and
18
+ * the write then found nothing to write. Backends must return `null` when the lookup misses.
19
+ */
20
+ readState: () => Promise<string | null | undefined>;
10
21
  /** Persist the record's new workflow state, written verbatim. */
11
22
  writeState: (nextState: string) => Promise<void>;
12
23
  /**
13
- * Persist record field data for a mutate-in-place self-transition, returning the full updated
14
- * record (so the client writeback reflects the new data). Optional: a backend with no data-write
15
- * path (e.g. PostGraphile today, which writes only `status`) omits it, and a self-transition is
16
- * then rejected loudly rather than silently dropped.
24
+ * Persist a record's field data for a self-transition, returning the full record as it now
25
+ * stands (so the client writeback reflects it).
26
+ *
27
+ * **This is an upsert, and it is the create path.** Saving a record is one request whether or
28
+ * not the row is there yet, so there is no create action and no create mutation — `exists` says
29
+ * which case you are in, and the second argument exists only because the dispatcher already
30
+ * knows: it read the record's state to run the guard. When `exists` is false, mint or derive the
31
+ * identity here and return the created record; identity is the backend's business, not the
32
+ * dispatcher's. Read the declared `primaryKey` out of `data` for a natural-keyed doctype — that
33
+ * value is a field the user filled in — and mint one only when the doctype is surrogate-keyed.
34
+ *
35
+ * Never return an empty object for a creation: the dispatcher treats that as a backend that
36
+ * only knows how to patch, and fails loudly rather than reporting a save that stored nothing.
37
+ *
38
+ * Optional. A backend with no data-write path omits it, which is how it declines both saving
39
+ * and creating; a self-transition is then rejected loudly rather than silently dropped — unless
40
+ * `runEffect` is supplied, in which case the handler is the persistence path.
17
41
  */
18
- writeData?: (patch: Record<string, unknown>) => Promise<Record<string, unknown>>;
42
+ writeData?: (patch: Record<string, unknown>, exists: boolean) => Promise<Record<string, unknown>>;
43
+ /**
44
+ * Run the adapter's side effect for this action, after the guard has passed and before any
45
+ * state is written. This is the seam a **database author** wires — see
46
+ * `StonecropPluginOptions.actionHandlers` for the Postgres adapter's registration surface.
47
+ *
48
+ * It is what makes a stateless Command (no `nextState`, no `selfTransition`) executable at
49
+ * all: without one, such an action has nothing to apply and fails loudly.
50
+ *
51
+ * Throwing rejects the action, so the dispatcher writes neither data nor state. It does **not**
52
+ * undo writes the handler already made: this guard is storage-agnostic and owns no transaction,
53
+ * and the Postgres adapter in particular dispatches outside one. A handler whose own statements
54
+ * must be all-or-nothing has to wrap them itself.
55
+ *
56
+ * Returning a full record makes it the client writeback payload; returning `undefined` leaves
57
+ * the doctype's own outcome to decide what comes back.
58
+ *
59
+ * @param currentState - The state the guard read, or `undefined` when nothing required reading it
60
+ * @returns The updated record, or `undefined` to leave the result payload to the state outcome
61
+ */
62
+ runEffect?: (currentState: string | undefined) => Promise<unknown>;
19
63
  }
20
64
  /**
21
- * Apply a workflow action's state transition on the server, enforcing `allowedStates`.
65
+ * Apply a workflow action on the server, enforcing `allowedStates`.
22
66
  *
23
67
  * The server owns the transition: it reads the record's authoritative current state,
24
- * rejects the action when `isActionAllowedInState` denies it, then writes `nextState`
25
- * verbatim. Storage access is injected via `io` so this one guard serves every backend
26
- * and can never disagree with the frontend's `getAvailableTransitions`, which shares the
27
- * same predicate.
68
+ * rejects the action when `isActionAllowedInState` denies it, then applies the outcome.
69
+ * Storage access is injected via `io` so this one guard serves every backend and can never
70
+ * disagree with the frontend's `getAvailableTransitions`, which shares the same predicate.
71
+ *
72
+ * **The doctype decides whether an action may run and what state results; the adapter decides
73
+ * what actually happens.** `allowedStates`, `nextState` and `selfTransition` are authored in the
74
+ * doctype (in DocBuilder, by whoever models the workflow); the effect is registered by whoever
75
+ * owns the database. Neither names the other: an action never carries a handler name, and a
76
+ * handler never overrides the guard.
28
77
  *
29
- * There are three action shapes this guard distinguishes:
78
+ * There are four action shapes this distinguishes:
30
79
  * - A cross-state **transition** (has `nextState`): writes the new `status`, guarded by `allowedStates`.
31
80
  * - A **self-transition** (`selfTransition: true`, no `nextState`, e.g. `Save`): stays in the current
32
81
  * state and persists record field `data` in place via `io.writeData`, guarded by `allowedStates`.
33
- * A backend without a data-write path rejects it loudly instead of dropping it silently.
34
- * - Anything else with no `nextState` and no `selfTransition` flag is a genuine authoring mistake (or a
35
- * stateless side-effect command whose server handler is not wired — the intended `callHandler` primitive
36
- * is still unimplemented): it fails loudly before touching the backend rather than reporting a false success.
82
+ * When the target record does not exist the same write creates it — saving a record is one
83
+ * request whether or not the row is there yet, so there is no separate create action, no create
84
+ * mutation, and no second write path for it.
85
+ * - A **stateless command** (neither of the above) with an `io.runEffect`: the handler is the whole
86
+ * outcome. Still guarded by `allowedStates`, and still forbidden from moving the record.
87
+ * - Anything else — no `nextState`, no `selfTransition`, no registered effect — is either a genuine
88
+ * authoring mistake or a command whose handler was never wired. It fails loudly before touching
89
+ * the backend rather than reporting a false success.
37
90
  *
38
91
  * @param actionDef - The action's `label`, `allowedStates`, and either `nextState` (transition) or `selfTransition`
39
- * @param io - Backend read/write closures
92
+ * @param io - Backend read/write closures, plus the optional adapter-owned effect
40
93
  * @param data - Record field data for a self-transition's mutate-in-place write (ignored by transitions)
41
- * @returns Action result envelope — the resulting `data.state` for a transition, the full record for a self-transition
94
+ * @returns Action result envelope — the freshest record the backend produced, or the resulting state
42
95
  * @public
43
96
  */
44
97
  export declare function applyGuardedTransition(actionDef: {
@@ -1 +1 @@
1
- {"version":3,"file":"transition.d.ts","sourceRoot":"","sources":["../../../src/dispatch/transition.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IACnC,2GAA2G;IAC3G,SAAS,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAA;IAC5C,iEAAiE;IACjE,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAChD;;;;;OAKG;IACH,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;CAChF;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBA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