@stonecrop/graphql-middleware 0.13.0 → 0.13.2

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/actions.ts","../src/registry/fetchHandlers.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 = { ...(data as object), 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\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.fieldtype === 'Link' && typeof field.options === 'string') {\n\t\t\t\tif (!doctypeRegistry.has(field.options)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'options'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${field.options}`,\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 { FieldMeta } from '@stonecrop/schema'\nimport type { ActionHandler } from '../types'\n\nconst handlerRegistry: Map<string, ActionHandler> = new Map()\n\n/**\n * Register an action handler\n * @param name - Unique name for the action handler\n * @param handler - Action handler function to register\n * @public\n */\nexport function registerHandler(name: string, handler: ActionHandler): void {\n\thandlerRegistry.set(name, handler)\n}\n\n/**\n * Get a registered handler by name\n * @param name - Name of the action handler to retrieve\n * @public\n */\nexport function getHandler(name: string): ActionHandler | undefined {\n\treturn handlerRegistry.get(name)\n}\n\n/**\n * Check if a handler is registered\n * @param name - Name of the action handler to check\n * @public\n */\nexport function hasHandler(name: string): boolean {\n\treturn handlerRegistry.has(name)\n}\n\n/**\n * Clear all registered handlers\n * @public\n */\nexport function clearHandlers(): void {\n\thandlerRegistry.clear()\n}\n\n// =============================================================================\n// Built-in Handlers\n// =============================================================================\n\n/**\n * Validate that all required fields are present in a record\n */\nconst validateRequiredFields: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst missing: string[] = []\n\tfor (const field of doctype.fields) {\n\t\tif (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {\n\t\t\tmissing.push(field.label ?? field.fieldname)\n\t\t}\n\t}\n\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Missing required fields: ${missing.join(', ')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate field types match expected types\n */\nconst validateFieldTypes: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst errors: string[] = []\n\n\tfor (const field of doctype.fields) {\n\t\tconst value = record[field.fieldname]\n\t\tif (value === undefined || value === null) continue\n\n\t\tconst error = validateFieldValue(field, value)\n\t\tif (error) errors.push(error)\n\t}\n\n\t// Validate link fields\n\tif (doctype.links) {\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst value = record[fieldname]\n\t\t\tif (value === undefined || value === null) continue\n\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\tif (isMany) {\n\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected array, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (typeof value !== 'object' || Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected object, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new Error(`Field type validation failed:\\n${errors.join('\\n')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate a single field value against its expected type\n */\nfunction validateFieldValue(field: FieldMeta, value: unknown): string | null {\n\tconst { fieldname, fieldtype } = field\n\n\tswitch (fieldtype) {\n\t\tcase 'Int':\n\t\t\tif (typeof value !== 'number' || !Number.isInteger(value)) {\n\t\t\t\treturn `${fieldname}: expected integer, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Float':\n\t\tcase 'Decimal':\n\t\tcase 'Currency':\n\t\tcase 'Quantity':\n\t\t\tif (typeof value !== 'number' && typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected number, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Check':\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\treturn `${fieldname}: expected boolean, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Data':\n\t\tcase 'Text':\n\t\tcase 'Code':\n\t\tcase 'Link':\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected string, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Date':\n\t\tcase 'Time':\n\t\tcase 'Datetime':\n\t\t\tif (typeof value !== 'string' && !(value instanceof Date)) {\n\t\t\t\treturn `${fieldname}: expected date string or Date, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'JSON':\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\treturn `${fieldname}: expected object, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\t}\n\n\treturn null\n}\n\n/**\n * No-op handler for testing or placeholder actions\n */\nconst noop: ActionHandler = async () => {\n\treturn { ok: true }\n}\n\n/**\n * Built-in handlers available for registration\n * @public\n */\nexport const builtinHandlers: Record<string, ActionHandler> = {\n\tvalidateRequiredFields,\n\tvalidateFieldTypes,\n\tnoop,\n}\n\n/**\n * Register all built-in handlers\n * @public\n */\nexport function registerBuiltinHandlers(): void {\n\tfor (const [name, handler] of Object.entries(builtinHandlers)) {\n\t\tregisterHandler(name, handler)\n\t}\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 { 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\tfieldname: String!\n\t\tfieldtype: String!\n\t\tcomponent: String\n\t\tlabel: String\n\t\twidth: String\n\t\talign: String\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\tedit: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\toptions: JSON\n\t\tmask: String\n\t\tprecision: Int\n\t\tscale: Int\n\t\tmode: String\n\t\tvalidation: JSON\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\thandler: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tconfirm: Boolean\n\t\targs: JSON\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\ttableName: 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 { DoctypeMeta, GetRecordOptions } 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 { getHandler } from '../registry/actions'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport { typeDefs } from '../typeDefs'\nimport type { ActionContext } from '../types'\n\n/**\n * Options for creating a Stonecrop PostGraphile plugin.\n * @public\n */\nexport interface StonecropPluginOptions {\n\t/**\n\t * Primary key column name used in all `stonecropRecord` lookups and linked-record fetches.\n\t * Defaults to `'id'`.\n\t */\n\tpkField?: string\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}\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\tconst pkField = options.pkField ?? 'id'\n\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// eslint-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\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(doctype as string)\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 = specs[i].doctype as string\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}> = new Array(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?.tableName) {\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 columns = getSqlColumns(meta, pkField)\n\t\t\t\t\t\t\t\t\t\tconst ids = indices.map(i => specs[i].id as string)\n\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 \"${meta.tableName}\" WHERE \"${pkField}\"::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[pkField]), 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 = specs[i].id as string\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') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = (fetch as { method: 'custom'; handler: string }).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\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?.tableName) continue\n\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst targetColumns = getSqlColumns(targetMeta, pkField)\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\tlet sql = `SELECT ${targetColumns} FROM \"${targetMeta.tableName}\" WHERE \"${link.backlink}\"::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\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 { 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 \"${targetMeta.tableName}\" WHERE \"${pkField}\" = $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 meta = getMeta(spec.doctype as string)\n\t\t\t\t\t\t\t\t\t\t\tif (!meta?.tableName) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn { data: [], doctype: spec.doctype as string, 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(meta.fields.map(f => f.fieldname))\n\t\t\t\t\t\t\t\t\t\t\tconst columns = getSqlColumns(meta, pkField)\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\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(`\"${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\tconst orderByStr = spec.orderBy as string\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 \"${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 \"${meta.tableName}\"${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\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(`\"${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<{ __count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS __count FROM \"${meta.tableName}\"${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]?.__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: spec.doctype as string, 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(spec.doctype as string)\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 handler = getHandler(actionDef.handler)\n\t\t\t\t\t\t\t\t\tif (!handler) {\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: `Handler not registered: ${actionDef.handler}`,\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 actionContext: ActionContext = { doctype: meta, pgClient }\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tconst result = await handler(spec.actionArgs ?? [], actionContext)\n\t\t\t\t\t\t\t\t\t\treturn { success: true, data: result, error: null }\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 helper — produces a quoted comma-separated column list for SELECT\n// ===========================================================================\n\n/**\n * Derive a quoted SQL column list from doctype field definitions.\n * Excludes Display fields (no backing DB column) and Link fields that have an\n * explicit `links` declaration (those are FK references, not scalar columns).\n * Always prepends the PK column when it is not already listed in `meta.fields`.\n */\nfunction getSqlColumns(meta: DoctypeMeta, pkField: string): string {\n\tconst linkedFieldnames = new Set<string>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinkedFieldnames.add((link as any).fieldname ?? key)\n\t\t}\n\t}\n\n\tconst columns: string[] = []\n\tconst hasPk = meta.fields.some(f => f.fieldname === pkField)\n\tif (!hasPk) {\n\t\tcolumns.push(`\"${pkField}\"`)\n\t}\n\n\tfor (const f of meta.fields) {\n\t\tif (f.fieldtype === 'Display') continue\n\t\tif (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname)) continue\n\t\tcolumns.push(`\"${f.fieldname}\"`)\n\t}\n\n\treturn columns.join(', ')\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// eslint-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// eslint-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","handlerRegistry","registerHandler","handler","getHandler","hasHandler","clearHandlers","validateRequiredFields","args","context","record","missing","validateFieldTypes","value","error","validateFieldValue","fieldname","link","fieldtype","noop","builtinHandlers","registerBuiltinHandlers","registry","registerFetchHandler","getFetchHandler","clearFetchHandlers","typeDefs","gql","createStonecropPlugin","pkField","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","i","results","indices","meta","columns","getSqlColumns","ids","rows","rowByPk","r","specId","row","rowData","recordOptions","includeAll","includeSet","linkName","fetch","isMany","effectiveMethod","effectiveLimit","handlerName","targetMeta","targetColumns","sql","linkValues","linked","fkValue","unknownLinks","$filters","$orderBy","$limit","$offset","spec","knownFields","f","values","whereClauses","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","actionDef","actionContext","linkedFieldnames","key","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,EAAYH,CAAG;AAE/B,aAAWI,KAASF,GAAS;AAC5B,UAAMG,IAAWC,EAAKN,GAAKI,CAAK;AAGhC,IAFaG,EAASF,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,EAAaF,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,EACxD;AAEA,QA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A,MACR,UAAUC,GAAU7I,GAAS8I,GAAS;AACrC,eAAO,KAAK,eAAe,KAAK,eAAeA,CAAO,CAAC;AAAA,MACxD;AAAA,IAAA;AAAA,EACD;AAEF,GAsBaC,KAAwB,CAAC/I,OAAoE;AAAA,EACzG,SAAS,CAACgJ,EAAuB;AAAA,EACjC,SAAShJ,GAAS,gBAAgB,WAAW,CAAC4I,EAA0B,IAAI,CAAA;AAC7E,IAmBaK,KAAyCF,GAAA;"}
1
+ {"version":3,"file":"index.js","sources":["../src/registry/doctypes.ts","../src/registry/actions.ts","../src/registry/fetchHandlers.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 = { ...(data as object), 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\n\t\tfor (const field of doctype.fields) {\n\t\t\tif (field.fieldtype === 'Link' && typeof field.options === 'string') {\n\t\t\t\tif (!doctypeRegistry.has(field.options)) {\n\t\t\t\t\terrors.push({\n\t\t\t\t\t\tpath: [doctype.name, 'fields', field.fieldname, 'options'],\n\t\t\t\t\t\tmessage: `Link references unknown doctype: ${field.options}`,\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 { FieldMeta } from '@stonecrop/schema'\nimport type { ActionHandler } from '../types'\n\nconst handlerRegistry: Map<string, ActionHandler> = new Map()\n\n/**\n * Register an action handler\n * @param name - Unique name for the action handler\n * @param handler - Action handler function to register\n * @public\n */\nexport function registerHandler(name: string, handler: ActionHandler): void {\n\thandlerRegistry.set(name, handler)\n}\n\n/**\n * Get a registered handler by name\n * @param name - Name of the action handler to retrieve\n * @public\n */\nexport function getHandler(name: string): ActionHandler | undefined {\n\treturn handlerRegistry.get(name)\n}\n\n/**\n * Check if a handler is registered\n * @param name - Name of the action handler to check\n * @public\n */\nexport function hasHandler(name: string): boolean {\n\treturn handlerRegistry.has(name)\n}\n\n/**\n * Clear all registered handlers\n * @public\n */\nexport function clearHandlers(): void {\n\thandlerRegistry.clear()\n}\n\n// =============================================================================\n// Built-in Handlers\n// =============================================================================\n\n/**\n * Validate that all required fields are present in a record\n */\nconst validateRequiredFields: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst missing: string[] = []\n\tfor (const field of doctype.fields) {\n\t\tif (field.required && (record[field.fieldname] === undefined || record[field.fieldname] === null)) {\n\t\t\tmissing.push(field.label ?? field.fieldname)\n\t\t}\n\t}\n\n\tif (missing.length > 0) {\n\t\tthrow new Error(`Missing required fields: ${missing.join(', ')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate field types match expected types\n */\nconst validateFieldTypes: ActionHandler = async (args, context) => {\n\tconst [record] = args as [Record<string, unknown>]\n\tconst { doctype } = context\n\n\tconst errors: string[] = []\n\n\tfor (const field of doctype.fields) {\n\t\tconst value = record[field.fieldname]\n\t\tif (value === undefined || value === null) continue\n\n\t\tconst error = validateFieldValue(field, value)\n\t\tif (error) errors.push(error)\n\t}\n\n\t// Validate link fields\n\tif (doctype.links) {\n\t\tfor (const [fieldname, link] of Object.entries(doctype.links)) {\n\t\t\tconst value = record[fieldname]\n\t\t\tif (value === undefined || value === null) continue\n\n\t\t\tconst isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne'\n\t\t\tif (isMany) {\n\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected array, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (typeof value !== 'object' || Array.isArray(value)) {\n\t\t\t\t\terrors.push(`${fieldname}: expected object, got ${typeof value}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length > 0) {\n\t\tthrow new Error(`Field type validation failed:\\n${errors.join('\\n')}`)\n\t}\n\n\treturn { valid: true }\n}\n\n/**\n * Validate a single field value against its expected type\n */\nfunction validateFieldValue(field: FieldMeta, value: unknown): string | null {\n\tconst { fieldname, fieldtype } = field\n\n\tswitch (fieldtype) {\n\t\tcase 'Int':\n\t\t\tif (typeof value !== 'number' || !Number.isInteger(value)) {\n\t\t\t\treturn `${fieldname}: expected integer, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Float':\n\t\tcase 'Decimal':\n\t\tcase 'Currency':\n\t\tcase 'Quantity':\n\t\t\tif (typeof value !== 'number' && typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected number, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Check':\n\t\t\tif (typeof value !== 'boolean') {\n\t\t\t\treturn `${fieldname}: expected boolean, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Data':\n\t\tcase 'Text':\n\t\tcase 'Code':\n\t\tcase 'Link':\n\t\t\tif (typeof value !== 'string') {\n\t\t\t\treturn `${fieldname}: expected string, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'Date':\n\t\tcase 'Time':\n\t\tcase 'Datetime':\n\t\t\tif (typeof value !== 'string' && !(value instanceof Date)) {\n\t\t\t\treturn `${fieldname}: expected date string or Date, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\n\t\tcase 'JSON':\n\t\t\tif (typeof value !== 'object') {\n\t\t\t\treturn `${fieldname}: expected object, got ${typeof value}`\n\t\t\t}\n\t\t\tbreak\n\t}\n\n\treturn null\n}\n\n/**\n * No-op handler for testing or placeholder actions\n */\nconst noop: ActionHandler = async () => {\n\treturn { ok: true }\n}\n\n/**\n * Built-in handlers available for registration\n * @public\n */\nexport const builtinHandlers: Record<string, ActionHandler> = {\n\tvalidateRequiredFields,\n\tvalidateFieldTypes,\n\tnoop,\n}\n\n/**\n * Register all built-in handlers\n * @public\n */\nexport function registerBuiltinHandlers(): void {\n\tfor (const [name, handler] of Object.entries(builtinHandlers)) {\n\t\tregisterHandler(name, handler)\n\t}\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 { 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\tfieldname: String!\n\t\tfieldtype: String!\n\t\tcomponent: String\n\t\tlabel: String\n\t\twidth: String\n\t\talign: String\n\t\trequired: Boolean\n\t\treadOnly: Boolean\n\t\tedit: Boolean\n\t\thidden: Boolean\n\t\tdefault: JSON\n\t\toptions: JSON\n\t\tmask: String\n\t\tprecision: Int\n\t\tscale: Int\n\t\tmode: String\n\t\tvalidation: JSON\n\t}\n\n\ttype StonecropWorkflowAction {\n\t\tlabel: String!\n\t\thandler: String!\n\t\trequiredFields: [String!]\n\t\tallowedStates: [String!]\n\t\tconfirm: Boolean\n\t\targs: JSON\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 { DoctypeMeta, FieldMeta, GetRecordOptions } from '@stonecrop/schema'\nimport { camelToSnake, pascalToSnake } 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 { getHandler } from '../registry/actions'\nimport { getFetchHandler } from '../registry/fetchHandlers'\nimport { getMeta, getAllMeta } from '../registry/doctypes'\nimport { typeDefs } from '../typeDefs'\nimport type { ActionContext } from '../types'\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// eslint-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\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(doctype as string)\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 = specs[i].doctype as string\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}> = new Array(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 => specs[i].id as string)\n\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 = specs[i].id as string\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') {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tconst handlerName = (fetch as { method: 'custom'; handler: string }).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\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\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\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 meta = getMeta(spec.doctype as string)\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: spec.doctype as string, 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(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\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\tconst orderByStr = spec.orderBy as string\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\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<{ __count: string }>(pgClient, {\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: `SELECT COUNT(*) AS __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]?.__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: spec.doctype as string, 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(spec.doctype as string)\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 handler = getHandler(actionDef.handler)\n\t\t\t\t\t\t\t\t\tif (!handler) {\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: `Handler not registered: ${actionDef.handler}`,\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 actionContext: ActionContext = { doctype: meta, pgClient }\n\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tconst result = await handler(spec.actionArgs ?? [], actionContext)\n\t\t\t\t\t\t\t\t\t\treturn { success: true, data: result, error: null }\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 * 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 Display fields (no backing DB column) and Link fields that have an\n * explicit `links` declaration (those are FK references, not scalar columns).\n *\n * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands\n */\nfunction getSqlColumns(meta: DoctypeMeta): string {\n\tconst linkedFieldnames = new Set<string>()\n\tif (meta.links) {\n\t\tfor (const [key, link] of Object.entries(meta.links)) {\n\t\t\tlinkedFieldnames.add((link as any).fieldname ?? key)\n\t\t}\n\t}\n\n\tconst columns: string[] = []\n\tfor (const f of meta.fields) {\n\t\tif (f.fieldtype === 'Display') continue\n\t\tif (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname)) continue\n\t\tconst col = camelToSnake(f.fieldname)\n\t\tcolumns.push(col !== f.fieldname ? `\"${col}\" AS \"${f.fieldname}\"` : `\"${f.fieldname}\"`)\n\t}\n\n\treturn columns.join(', ')\n}\n\n/**\n * Find the field declared with fieldtype 'PrimaryKey' in the doctype.\n * Returns undefined when no PrimaryKey field is declared (PK-less doctypes).\n *\n * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands\n */\nfunction getPkMeta(meta: DoctypeMeta): FieldMeta | undefined {\n\treturn meta.fields.find(f => f.fieldtype === 'PrimaryKey')\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// eslint-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// eslint-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","handlerRegistry","registerHandler","handler","getHandler","hasHandler","clearHandlers","validateRequiredFields","args","context","record","missing","validateFieldTypes","value","error","validateFieldValue","fieldname","link","fieldtype","noop","builtinHandlers","registerBuiltinHandlers","registry","registerFetchHandler","getFetchHandler","clearFetchHandlers","typeDefs","gql","createStonecropPlugin","debugSql","pgClient","query","extendSchema","build","pgExecutors","executor","_","$doctype","lambda","constant","$id","$options","loadOneWithPgClient","object","specs","byDoctype","d","results","indices","meta","i","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","values","whereClauses","whereClause","orderByClause","orderByStr","lastUnder","fieldName","pagingClause","count","countValues","countWhere","countWhereClause","countRows","$action","$actionArgs","sideEffectWithPgClient","actionDef","actionContext","linkedFieldnames","key","f","col","tables","target","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,EA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;AAAA,MACxD;AAAA,IAAA;AAAA,EACD;AAEF,GAsBaC,KAAwB,CAAC5J,OAAoE;AAAA,EACzG,SAAS,CAAC6J,EAAuB;AAAA,EACjC,SAAS7J,GAAS,gBAAgB,WAAW,CAACyJ,EAA0B,IAAI,CAAA;AAC7E,IAmBaK,KAAyCF,GAAA;"}
@@ -4,16 +4,18 @@ import { GraphileConfig } from 'postgraphile/graphile-build';
4
4
  * @public
5
5
  */
6
6
  export interface StonecropPluginOptions {
7
- /**
8
- * Primary key column name used in all `stonecropRecord` lookups and linked-record fetches.
9
- * Defaults to `'id'`.
10
- */
11
- pkField?: string;
12
7
  /**
13
8
  * When `true`, SQL queries executed inside `loadOneWithPgClient` callbacks
14
9
  * are logged to `console.log` with `[@stonecrop/graphql-middleware]` prefix. Defaults to `false`.
15
10
  */
16
11
  debug?: boolean;
12
+ /**
13
+ * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.
14
+ * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).
15
+ * SQL fragments and subqueries are not supported.
16
+ * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
17
+ */
18
+ tables?: Record<string, string>;
17
19
  }
18
20
  /**
19
21
  * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
@@ -1 +1 @@
1
- {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAS5D;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;CACf;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MAkU3F,CAAA"}
1
+ {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAS5D;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MA0U3F,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { camelToSnake, pascalToSnake } from '@stonecrop/schema';
1
2
  import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
2
3
  import { constant, lambda, object } from 'postgraphile/grafast';
3
4
  import { extendSchema } from 'postgraphile/utils';
@@ -16,7 +17,6 @@ import { typeDefs } from '../typeDefs';
16
17
  * @public
17
18
  */
18
19
  export const createStonecropPlugin = (options = {}) => {
19
- const pkField = options.pkField ?? 'id';
20
20
  /**
21
21
  * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging
22
22
  * for queries that run inside custom loadOneWithPgClient callbacks, which
@@ -63,19 +63,26 @@ export const createStonecropPlugin = (options = {}) => {
63
63
  const results = new Array(specs.length);
64
64
  for (const [doctype, indices] of byDoctype) {
65
65
  const meta = getMeta(doctype);
66
- if (!meta?.tableName) {
66
+ if (!meta) {
67
67
  for (const i of indices)
68
68
  results[i] = { data: null, doctype };
69
69
  continue;
70
70
  }
71
- const columns = getSqlColumns(meta, pkField);
71
+ const pkMeta = getPkMeta(meta);
72
+ if (!pkMeta) {
73
+ for (const i of indices)
74
+ results[i] = { data: null, doctype };
75
+ continue;
76
+ }
77
+ const pkColumn = camelToSnake(pkMeta.fieldname);
78
+ const columns = getSqlColumns(meta);
72
79
  const ids = indices.map(i => specs[i].id);
73
80
  const { rows } = await debugSql(pgClient, {
74
- text: `SELECT ${columns} FROM "${meta.tableName}" WHERE "${pkField}"::text = ANY($1::text[])`,
81
+ text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
75
82
  values: [ids],
76
83
  });
77
84
  // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
78
- const rowByPk = new Map(rows.map(r => [String(r[pkField]), r]));
85
+ const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
79
86
  for (const i of indices) {
80
87
  const specId = specs[i].id;
81
88
  const row = rowByPk.get(specId);
@@ -110,13 +117,14 @@ export const createStonecropPlugin = (options = {}) => {
110
117
  if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
111
118
  continue;
112
119
  const targetMeta = getMeta(link.target);
113
- if (!targetMeta?.tableName)
120
+ if (!targetMeta)
114
121
  continue;
115
- const targetColumns = getSqlColumns(targetMeta, pkField);
122
+ const targetColumns = getSqlColumns(targetMeta);
116
123
  if (isMany) {
117
124
  if (!link.backlink)
118
125
  continue;
119
- let sql = `SELECT ${targetColumns} FROM "${targetMeta.tableName}" WHERE "${link.backlink}"::text = $1`;
126
+ const backlinkCol = camelToSnake(link.backlink);
127
+ let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
120
128
  const linkValues = [specId];
121
129
  if (effectiveLimit != null) {
122
130
  sql += ` LIMIT $2`;
@@ -136,8 +144,12 @@ export const createStonecropPlugin = (options = {}) => {
136
144
  rowData[linkName] = null;
137
145
  continue;
138
146
  }
147
+ const targetPkMeta = getPkMeta(targetMeta);
148
+ if (!targetPkMeta)
149
+ continue;
150
+ const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
139
151
  const { rows: linked } = await debugSql(pgClient, {
140
- text: `SELECT ${targetColumns} FROM "${targetMeta.tableName}" WHERE "${pkField}" = $1`,
152
+ text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
141
153
  values: [fkValue],
142
154
  });
143
155
  rowData[linkName] = linked[0] ?? null;
@@ -166,11 +178,11 @@ export const createStonecropPlugin = (options = {}) => {
166
178
  }), async (pgClient, specs) => {
167
179
  return await Promise.all(specs.map(async (spec) => {
168
180
  const meta = getMeta(spec.doctype);
169
- if (!meta?.tableName) {
181
+ if (!meta) {
170
182
  return { data: [], doctype: spec.doctype, count: 0 };
171
183
  }
172
184
  const knownFields = new Set(meta.fields.map(f => f.fieldname));
173
- const columns = getSqlColumns(meta, pkField);
185
+ const columns = getSqlColumns(meta);
174
186
  const values = [];
175
187
  // WHERE from filters (parameterised — safe against SQL injection)
176
188
  const whereClauses = [];
@@ -180,7 +192,7 @@ export const createStonecropPlugin = (options = {}) => {
180
192
  throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
181
193
  }
182
194
  values.push(value);
183
- whereClauses.push(`"${field}" = $${values.length}`);
195
+ whereClauses.push(`"${camelToSnake(field)}" = $${values.length}`);
184
196
  }
185
197
  }
186
198
  const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
@@ -200,7 +212,7 @@ export const createStonecropPlugin = (options = {}) => {
200
212
  if (!knownFields.has(fieldName)) {
201
213
  throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
202
214
  }
203
- orderByClause = ` ORDER BY "${fieldName}" ${dir}`;
215
+ orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
204
216
  }
205
217
  // LIMIT / OFFSET
206
218
  let pagingClause = '';
@@ -213,7 +225,7 @@ export const createStonecropPlugin = (options = {}) => {
213
225
  pagingClause += ` OFFSET $${values.length}`;
214
226
  }
215
227
  const { rows } = await debugSql(pgClient, {
216
- text: `SELECT ${columns} FROM "${meta.tableName}"${whereClause}${orderByClause}${pagingClause}`,
228
+ text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
217
229
  values,
218
230
  });
219
231
  // Total count matching filters (independent of LIMIT/OFFSET)
@@ -226,12 +238,12 @@ export const createStonecropPlugin = (options = {}) => {
226
238
  if (!knownFields.has(field))
227
239
  continue;
228
240
  countValues.push(value);
229
- countWhere.push(`"${field}" = $${countValues.length}`);
241
+ countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
230
242
  }
231
243
  }
232
244
  const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : '';
233
245
  const { rows: countRows } = await debugSql(pgClient, {
234
- text: `SELECT COUNT(*) AS __count FROM "${meta.tableName}"${countWhereClause}`,
246
+ text: `SELECT COUNT(*) AS __count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,
235
247
  values: countValues,
236
248
  });
237
249
  count = parseInt(countRows[0]?.__count ?? '0', 10);
@@ -291,15 +303,18 @@ export const createStonecropPlugin = (options = {}) => {
291
303
  });
292
304
  };
293
305
  // ===========================================================================
294
- // SQL column helper — produces a quoted comma-separated column list for SELECT
306
+ // SQL column helpers
295
307
  // ===========================================================================
296
308
  /**
297
309
  * Derive a quoted SQL column list from doctype field definitions.
310
+ * Applies camelToSnake to each fieldname to get the DB column name, then
311
+ * aliases it back to the fieldname so result rows carry API-layer keys.
298
312
  * Excludes Display fields (no backing DB column) and Link fields that have an
299
313
  * explicit `links` declaration (those are FK references, not scalar columns).
300
- * Always prepends the PK column when it is not already listed in `meta.fields`.
314
+ *
315
+ * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
301
316
  */
302
- function getSqlColumns(meta, pkField) {
317
+ function getSqlColumns(meta) {
303
318
  const linkedFieldnames = new Set();
304
319
  if (meta.links) {
305
320
  for (const [key, link] of Object.entries(meta.links)) {
@@ -307,16 +322,36 @@ function getSqlColumns(meta, pkField) {
307
322
  }
308
323
  }
309
324
  const columns = [];
310
- const hasPk = meta.fields.some(f => f.fieldname === pkField);
311
- if (!hasPk) {
312
- columns.push(`"${pkField}"`);
313
- }
314
325
  for (const f of meta.fields) {
315
326
  if (f.fieldtype === 'Display')
316
327
  continue;
317
328
  if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
318
329
  continue;
319
- columns.push(`"${f.fieldname}"`);
330
+ const col = camelToSnake(f.fieldname);
331
+ columns.push(col !== f.fieldname ? `"${col}" AS "${f.fieldname}"` : `"${f.fieldname}"`);
320
332
  }
321
333
  return columns.join(', ');
322
334
  }
335
+ /**
336
+ * Find the field declared with fieldtype 'PrimaryKey' in the doctype.
337
+ * Returns undefined when no PrimaryKey field is declared (PK-less doctypes).
338
+ *
339
+ * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
340
+ */
341
+ function getPkMeta(meta) {
342
+ return meta.fields.find(f => f.fieldtype === 'PrimaryKey');
343
+ }
344
+ /**
345
+ * Resolve the PostgreSQL FROM clause target for a doctype.
346
+ * Uses the `tables` override map first; falls back to camelToSnake(name).
347
+ * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
348
+ * Values must be bare identifiers or schema.table pairs — not SQL fragments.
349
+ */
350
+ function resolveTableName(name, tables) {
351
+ const target = tables?.[name] ?? pascalToSnake(name);
352
+ const dotIndex = target.indexOf('.');
353
+ if (dotIndex > 0) {
354
+ return `"${target.slice(0, dotIndex)}"."${target.slice(dotIndex + 1)}"`;
355
+ }
356
+ return `"${target}"`;
357
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,gCA+EpB,CAAA"}
1
+ {"version":3,"file":"typeDefs.d.ts","sourceRoot":"","sources":["../../src/typeDefs.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,eAAO,MAAM,QAAQ,gCA8EpB,CAAA"}
@@ -42,7 +42,6 @@ export const typeDefs = gql `
42
42
  type StonecropDoctypeMeta {
43
43
  name: String!
44
44
  slug: String
45
- tableName: String
46
45
  fields: [StonecropFieldMeta!]!
47
46
  workflow: StonecropWorkflowMeta
48
47
  inherits: String
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.13.0",
3
+ "version": "0.13.2",
4
4
  "type": "module",
5
5
  "types": "./dist/graphql-middleware.d.ts",
6
6
  "exports": {
@@ -18,7 +18,7 @@
18
18
  "graphql": "^16.14.0",
19
19
  "pluralize": "^8.0.0",
20
20
  "postgraphile": "^5.0.3",
21
- "@stonecrop/schema": "0.13.0"
21
+ "@stonecrop/schema": "0.13.2"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@electric-sql/pglite": "^0.4.5",