@cyphra/better-auth 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapter.ts","../src/merge.ts","../src/schema.ts","../src/naming.ts","../src/where.ts","../src/options.ts","../src/legacy.ts"],"sourcesContent":["import {\n createAdapterFactory,\n type AdapterFactory,\n type AdapterFactoryConfig,\n type AdapterFactoryCustomizeAdapterCreator,\n type CleanedWhere,\n type CustomAdapter,\n type DBAdapterDebugLogOption,\n type DBTransactionAdapter,\n type JoinConfig,\n} from \"better-auth/adapters\";\nimport type { BetterAuthOptions } from \"better-auth/types\";\nimport { createOrm, type CyphraClient } from \"@cyphra/runtime\";\nimport { mergeAuthSchema } from \"./merge.js\";\nimport { deriveAuthGraph, type AuthGraph, type ModelMapping } from \"./schema.js\";\nimport { coerceScalar, fieldOf, toCyphraWhere } from \"./where.js\";\n\n/** Options for {@link cyphraAdapter}. Pass `client` or `db`. */\nexport interface CyphraAdapterConfig {\n /** A Cyphra client (`new CyphraClient({ uri, user, password })`). */\n client?: CyphraClient;\n /** Your generated Cyphra ORM client; its connection (`db.$client`) is reused. */\n db?: { readonly $client: CyphraClient };\n /** Use plural model names (`users`, `sessions`, …). Default `false`. */\n usePlural?: boolean;\n /**\n * Better Auth adapter debug logs. Leave off in production: logs can contain tokens and\n * other sensitive values.\n */\n debugLogs?: DBAdapterDebugLogOption;\n}\n\ntype Row = Record<string, unknown>;\ntype Args = Record<string, unknown>;\n\ntype Delegate = {\n findMany(args: Args): Promise<Row[]>;\n findFirst(args: Args): Promise<Row | null>;\n count(args: Args): Promise<number>;\n create(args: Args): Promise<Row>;\n update(args: Args): Promise<Row>;\n updateMany(args: Args): Promise<{ count: number }>;\n deleteMany(args: Args): Promise<{ count: number }>;\n};\n\n/** An ORM client or a transaction client built from the auth schema. */\ntype Db = Record<string, unknown> & {\n $cypher(strings: TemplateStringsArray, ...values: unknown[]): Promise<Row[]>;\n};\n\n/** The client to run operations on, and how to run several writes atomically. */\ninterface Source {\n readonly db: Db;\n write<T>(fn: (tx: Db) => Promise<T>): Promise<T>;\n}\n\n/** Property set and removed at once to take a node's write lock. */\nconst LOCK_FLAG = \"__cyphraLock\";\n\nfunction quote(id: string): string {\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n}\n\n/**\n * Take the write lock on the nodes `(:node {field: value})`. Neo4j holds it until the\n * transaction ends, so concurrent writers on the same node run one after the other.\n */\nasync function lockNode(db: Db, node: string, field: string, value: unknown): Promise<void> {\n const head = `MATCH (n:${quote(node)}) WHERE n.${quote(field)} = `;\n const flag = `n.${quote(LOCK_FLAG)}`;\n const tail = ` SET ${flag} = true REMOVE ${flag} RETURN count(n) AS c`;\n const strings = Object.assign([head, tail], { raw: [head, tail] });\n await db.$cypher(strings, value);\n}\n\nfunction fail(message: string): never {\n throw new Error(`@cyphra/better-auth: ${message}`);\n}\n\nfunction createOperations(\n source: (graph: AuthGraph) => Source,\n onInit?: (graph: AuthGraph, source: Source) => void,\n): AdapterFactoryCustomizeAdapterCreator {\n return (ctx) => {\n const graph = deriveAuthGraph(ctx);\n const src = source(graph);\n onInit?.(graph, src);\n\n const modelOf = (model: string, modelKey?: string): ModelMapping =>\n graph.models.get(modelKey ?? ctx.getDefaultModelName(model)) ??\n fail(`unknown model \"${model}\".`);\n const parentOf = (key: string) => graph.models.get(key)!;\n const delegate = (db: Db, m: ModelMapping) => db[m.delegate] as Delegate;\n const whereOf = (m: ModelMapping, where: readonly CleanedWhere[] | undefined) =>\n toCyphraWhere(m, where, parentOf);\n const childrenOf = (m: ModelMapping) =>\n [...graph.models.values()].flatMap((c) =>\n c.foreignKeys.filter((fk) => fk.parentKey === m.key).map((fk) => ({ child: c, fk })),\n );\n\n /** Database field names for a Better Auth `select` (schema or database names). */\n const selected = (m: ModelMapping, select?: readonly string[]): string[] =>\n select?.length\n ? select.map((s) => (m.fields.has(s) ? s : ctx.getFieldName({ model: m.key, field: s })))\n : [...m.fields.keys()];\n\n /** Cyphra `select`: scalars directly, foreign keys through their edge. */\n function selectOf(m: ModelMapping, select?: readonly string[]): Args {\n const out: Args = {};\n for (const name of selected(m, select)) {\n const f = fieldOf(m, name);\n if (f.kind === \"scalar\") out[name] = true;\n else out[f.relation] = { select: { [f.refField]: true } };\n }\n return out;\n }\n\n /** A Cyphra record back to the row shape Better Auth expects. */\n function toRow(m: ModelMapping, rec: Row, select?: readonly string[]): Row {\n const out: Row = {};\n for (const name of selected(m, select)) {\n const f = fieldOf(m, name);\n if (f.kind === \"scalar\") out[name] = rec[name] ?? null;\n else out[name] = (rec[f.relation] as Row | null | undefined)?.[f.refField] ?? null;\n }\n return out;\n }\n\n /** Better Auth data → Cyphra data: foreign keys become `connect` / `disconnect`. */\n function writeData(m: ModelMapping, data: Row, mode: \"create\" | \"update\"): Args {\n const out: Args = {};\n for (const [key, value] of Object.entries(data)) {\n if (value === undefined) continue;\n const f = fieldOf(m, key);\n if (f.kind === \"scalar\") out[key] = coerceScalar(f, value);\n else if (value !== null) out[f.relation] = { connect: { [f.refField]: value } };\n else if (mode === \"update\") out[f.relation] = { disconnect: true };\n }\n return out;\n }\n\n /**\n * Neo4j has no unique constraint on \"the edge to a given parent\", so `unique` foreign keys\n * are checked here, with the parent locked so that concurrent writes cannot both pass.\n */\n async function assertUniqueForeignKeys(\n tx: Db,\n m: ModelMapping,\n data: Row,\n selfId: unknown,\n ): Promise<void> {\n for (const fk of m.foreignKeys) {\n const value = data[fk.name];\n if (!fk.unique || value === undefined || value === null) continue;\n const parent = parentOf(fk.parentKey);\n await lockNode(tx, parent.node, fk.refField, value);\n const where: Args = { [fk.relation]: { is: { [fk.refField]: value } } };\n if (selfId !== undefined) where[m.idField] = { not: selfId };\n if ((await delegate(tx, m).count({ where })) > 0) {\n fail(`unique constraint failed on ${m.dbName}.${fk.name} = ${JSON.stringify(value)}.`);\n }\n }\n }\n\n /**\n * Delete the nodes of `m` matching `where`. Children are handled first, in the same\n * transaction, according to `references.onDelete`: `cascade` (Better Auth's default) deletes\n * them, `restrict` / `no action` refuse the delete, `set null` / `set default` just lose the\n * edge (DETACH DELETE removes it).\n */\n async function deleteWhere(\n tx: Db,\n m: ModelMapping,\n where: Args,\n lineage: ReadonlySet<string> = new Set(),\n ): Promise<number> {\n const next = new Set([...lineage, m.key]);\n for (const { child, fk } of childrenOf(m)) {\n const childWhere = { [fk.relation]: { is: where } };\n if (fk.onDelete === \"restrict\" || fk.onDelete === \"no action\") {\n if ((await delegate(tx, child).count({ where: childWhere })) > 0) {\n fail(\n `cannot delete ${m.dbName}: ${child.dbName}.${fk.name} references it (onDelete: \"${fk.onDelete}\").`,\n );\n }\n } else if (fk.onDelete === \"cascade\" && !lineage.has(child.key)) {\n await deleteWhere(tx, child, childWhere, next);\n }\n }\n return (await delegate(tx, m).deleteMany({ where })).count;\n }\n\n /** Find one matching node and take its write lock; `null` if it is gone by then. */\n async function lockOne(tx: Db, m: ModelMapping, where: Args): Promise<unknown> {\n const first = await delegate(tx, m).findFirst({ where, select: { [m.idField]: true } });\n if (!first) return null;\n const id = first[m.idField];\n await lockNode(tx, m.node, m.idField, id);\n // Re-check under the lock: a concurrent writer may have changed or deleted the node.\n const still = await delegate(tx, m).count({ where: { AND: [where, { [m.idField]: id }] } });\n return still === 1 ? id : null;\n }\n\n /** Native joins: follow the edges in the same query (`include` on the relation field). */\n function joinPlan(m: ModelMapping, join: JoinConfig | undefined) {\n const select: Args = {};\n const readers: ((rec: Row, out: Row) => void)[] = [];\n for (const [name, cfg] of Object.entries(join ?? {})) {\n const jm = modelOf(name, cfg.modelKey);\n const forward = jm.foreignKeys.find(\n (fk) => fk.parentKey === m.key && fk.name === cfg.on.to,\n );\n const backward = m.foreignKeys.find(\n (fk) => fk.parentKey === jm.key && fk.name === cfg.on.from,\n );\n const field = forward?.inverse ?? backward?.relation;\n if (!field) continue; // let Better Auth fall back to separate queries\n const many = Boolean(forward);\n select[field] = {\n select: selectOf(jm),\n ...(many && cfg.limit !== undefined ? { take: cfg.limit } : {}),\n };\n readers.push((rec, out) => {\n const v = rec[field];\n const rows = (many ? (v as Row[]) : v ? [v as Row] : []).map((r) => toRow(jm, r));\n out[name] = cfg.relation === \"one-to-one\" ? (rows[0] ?? null) : rows;\n });\n }\n return {\n select,\n read: (rec: Row, out: Row) => {\n for (const r of readers) r(rec, out);\n return out;\n },\n };\n }\n\n function orderByOf(m: ModelMapping, sortBy?: { field: string; direction: \"asc\" | \"desc\" }) {\n if (!sortBy) return undefined;\n const f = fieldOf(m, sortBy.field);\n if (f.kind !== \"scalar\")\n fail(`sorting by the foreign key ${m.dbName}.${f.name} is not supported.`);\n return { [f.name]: sortBy.direction };\n }\n\n const adapter: CustomAdapter = {\n create: async ({ model, modelKey, data, select }) => {\n const m = modelOf(model, modelKey);\n return src.write(async (tx) => {\n await assertUniqueForeignKeys(tx, m, data, undefined);\n const rec = await delegate(tx, m).create({\n data: writeData(m, data, \"create\"),\n select: selectOf(m),\n });\n return toRow(m, rec, select) as typeof data;\n });\n },\n\n findOne: async <T>({\n model,\n modelKey,\n where,\n select,\n join,\n }: {\n model: string;\n modelKey?: string;\n where: CleanedWhere[];\n select?: string[];\n join?: JoinConfig;\n }) => {\n const m = modelOf(model, modelKey);\n const plan = joinPlan(m, join);\n const rec = await delegate(src.db, m).findFirst({\n where: whereOf(m, where),\n select: { ...selectOf(m, select), ...plan.select },\n });\n return (rec ? plan.read(rec, toRow(m, rec, select)) : null) as T | null;\n },\n\n findMany: async <T>({\n model,\n modelKey,\n where,\n limit,\n sortBy,\n offset,\n select,\n join,\n }: {\n model: string;\n modelKey?: string;\n where?: CleanedWhere[];\n limit: number;\n sortBy?: { field: string; direction: \"asc\" | \"desc\" };\n offset?: number;\n select?: string[];\n join?: JoinConfig;\n }) => {\n const m = modelOf(model, modelKey);\n const plan = joinPlan(m, join);\n const recs = await delegate(src.db, m).findMany({\n where: whereOf(m, where),\n select: { ...selectOf(m, select), ...plan.select },\n orderBy: orderByOf(m, sortBy),\n ...(offset ? { skip: offset } : {}),\n ...(limit !== undefined && limit >= 0 ? { take: limit } : {}),\n });\n return recs.map((rec) => plan.read(rec, toRow(m, rec, select))) as T[];\n },\n\n count: async ({ model, modelKey, where }) => {\n const m = modelOf(model, modelKey);\n return delegate(src.db, m).count({ where: whereOf(m, where) });\n },\n\n update: async <T>({\n model,\n modelKey,\n where,\n update,\n }: {\n model: string;\n modelKey?: string;\n where: CleanedWhere[];\n update: T;\n }) => {\n if (!where.length) return null;\n const m = modelOf(model, modelKey);\n return src.write(async (tx) => {\n const first = await delegate(tx, m).findFirst({\n where: whereOf(m, where),\n select: { [m.idField]: true },\n });\n if (!first) return null;\n const id = first[m.idField];\n await assertUniqueForeignKeys(tx, m, update as Row, id);\n const rec = await delegate(tx, m).update({\n where: { [m.idField]: id },\n data: writeData(m, update as Row, \"update\"),\n select: selectOf(m),\n });\n return toRow(m, rec) as T;\n });\n },\n\n updateMany: async ({ model, modelKey, where, update }) => {\n const m = modelOf(model, modelKey);\n const data = writeData(m, update, \"update\");\n const touchesEdges = m.foreignKeys.some((fk) => update[fk.name] !== undefined);\n if (!touchesEdges) {\n return (await delegate(src.db, m).updateMany({ where: whereOf(m, where), data })).count;\n }\n return src.write(async (tx) => {\n const ids = await delegate(tx, m).findMany({\n where: whereOf(m, where),\n select: { [m.idField]: true },\n });\n for (const rec of ids) {\n await assertUniqueForeignKeys(tx, m, update, rec[m.idField]);\n await delegate(tx, m).update({ where: { [m.idField]: rec[m.idField] }, data });\n }\n return ids.length;\n });\n },\n\n delete: async ({ model, modelKey, where }) => {\n const m = modelOf(model, modelKey);\n await src.write((tx) => deleteWhere(tx, m, whereOf(m, where)));\n },\n\n deleteMany: async ({ model, modelKey, where }) => {\n const m = modelOf(model, modelKey);\n return src.write((tx) => deleteWhere(tx, m, whereOf(m, where)));\n },\n\n /**\n * Atomic find-and-delete of one row: lock it, re-check the predicate, delete it. Of N\n * concurrent callers on the same row, one gets the row and the others get `null`.\n */\n consumeOne: async <T>({\n model,\n modelKey,\n where,\n }: {\n model: string;\n modelKey?: string;\n where: CleanedWhere[];\n }) => {\n const m = modelOf(model, modelKey);\n return src.write(async (tx) => {\n const id = await lockOne(tx, m, whereOf(m, where));\n if (id === null) return null;\n const byId = { [m.idField]: id };\n const rec = await delegate(tx, m).findFirst({ where: byId, select: selectOf(m) });\n if (!rec) return null;\n await deleteWhere(tx, m, byId);\n return toRow(m, rec) as T;\n });\n },\n\n /** Guarded atomic counter update on one row (`where` is both selector and guard). */\n incrementOne: async <T>({\n model,\n modelKey,\n where,\n increment,\n set,\n }: {\n model: string;\n modelKey?: string;\n where: CleanedWhere[];\n increment: Record<string, number>;\n set?: Record<string, unknown>;\n }) => {\n const m = modelOf(model, modelKey);\n return src.write(async (tx) => {\n const id = await lockOne(tx, m, whereOf(m, where));\n if (id === null) return null;\n const data = writeData(m, (set ?? {}) as Row, \"update\");\n for (const [key, delta] of Object.entries(increment)) {\n const f = fieldOf(m, key);\n if (f.kind !== \"scalar\") fail(`cannot increment the foreign key ${m.dbName}.${key}.`);\n data[key] = { increment: delta };\n }\n await assertUniqueForeignKeys(tx, m, (set ?? {}) as Row, id);\n const rec = await delegate(tx, m).update({\n where: { [m.idField]: id },\n data,\n select: selectOf(m),\n });\n return toRow(m, rec) as T;\n });\n },\n\n createSchema: async ({ file, tables }) => {\n const authGraph = deriveAuthGraph({\n schema: tables,\n getModelName: ctx.getModelName,\n getFieldName: ctx.getFieldName,\n });\n const { readFile } = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n const target = file ?? (await configuredSchemaPath(readFile)) ?? \"schema.cyphra\";\n let existing: string | undefined;\n try {\n existing = await readFile(path.resolve(process.cwd(), target), \"utf8\");\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") throw e;\n }\n return {\n code: mergeAuthSchema(existing, authGraph.document),\n path: target,\n overwrite: true,\n };\n },\n };\n return adapter;\n };\n}\n\n/** The `schema` path from `cyphra.json` in the working directory, if there is one. */\nasync function configuredSchemaPath(\n readFile: (p: string, enc: \"utf8\") => Promise<string>,\n): Promise<string | undefined> {\n try {\n const config = JSON.parse(await readFile(\"cyphra.json\", \"utf8\")) as { schema?: unknown };\n return typeof config.schema === \"string\" ? config.schema : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Better Auth database adapter for Neo4j, built on the Cyphra ORM runtime.\n *\n * The Cyphra schema is derived from your Better Auth configuration (plugins included) at\n * runtime. Foreign keys are stored as edges: `Session.userId` is the edge\n * `(User)-[:HAS_SESSION]->(Session)`.\n *\n * @example\n * ```ts\n * import { betterAuth } from \"better-auth\";\n * import { cyphraAdapter } from \"@cyphra/better-auth\";\n * import { db } from \"./db\"; // your generated Cyphra client\n *\n * export const auth = betterAuth({ database: cyphraAdapter({ db }) });\n * ```\n */\nexport function cyphraAdapter(config: CyphraAdapterConfig): AdapterFactory<BetterAuthOptions> {\n const client = config.client ?? config.db?.$client;\n if (!client) fail(\"pass `client` (a CyphraClient) or `db` (a Cyphra ORM client).\");\n\n /** Better Auth passes its options when it builds the adapter; transactions need them again. */\n let resolvedOptions: BetterAuthOptions | undefined;\n let root: { graph: AuthGraph; source: Source } | undefined;\n\n const base: AdapterFactoryConfig = {\n adapterId: \"cyphra\",\n adapterName: \"Cyphra (Neo4j)\",\n usePlural: config.usePlural ?? false,\n debugLogs: config.debugLogs ?? false,\n supportsJSON: false,\n supportsDates: true,\n supportsBooleans: true,\n supportsArrays: true,\n supportsNumericIds: false,\n supportsUUIDs: false,\n };\n\n const factoryConfig: AdapterFactoryConfig = {\n ...base,\n transaction: (callback) => {\n if (!resolvedOptions || !root) fail(\"adapter used before Better Auth initialized it.\");\n const options = resolvedOptions;\n return root.source.write((tx) => {\n const inTx = createAdapterFactory({\n config: { ...base, transaction: false },\n adapter: createOperations(() => ({ db: tx, write: (fn) => fn(tx) })),\n });\n return callback(inTx(options) as DBTransactionAdapter);\n });\n },\n };\n\n const factory = createAdapterFactory({\n config: factoryConfig,\n adapter: createOperations(\n (graph) => {\n const orm = createOrm(graph.schema, { client }) as unknown as Db & {\n $transaction<T>(fn: (tx: Db) => Promise<T>): Promise<T>;\n };\n return { db: orm, write: (fn) => orm.$transaction(fn) };\n },\n (graph, source) => {\n root = { graph, source };\n },\n ),\n });\n\n return (options) => {\n resolvedOptions = options;\n return factory(options);\n };\n}\n","/**\n * Writes the Better Auth nodes into an existing `schema.cyphra` without touching anything else.\n *\n * Fields of auth nodes that Better Auth defines are added or updated in place, line by line.\n * Everything else is kept as written, comments included: your own models, relationships, and\n * fields you added to auth nodes (for example `projects Project[]` on `User`).\n *\n * @packageDocumentation\n */\n\nimport {\n parseSchema,\n printSchemaDocument,\n resolveSchema,\n type NodeDeclaration,\n type NodeField,\n type SchemaDocument,\n} from \"@cyphra/schema\";\n\nconst HEADER = `// Better Auth models, written by @cyphra/better-auth (npx @better-auth/cli generate).\n// You can add fields and relations to these nodes and add your own models: running the\n// generator again updates the Better Auth fields and keeps the rest.\n`;\n\n/** One field formatted as a `.cyphra` line (without indentation). */\nfunction formatField(field: NodeField): string {\n const text = printSchemaDocument({\n kind: \"Document\",\n declarations: [{ kind: \"Node\", name: \"X\", fields: [field] }],\n });\n return text.split(\"\\n\")[1]!.trim();\n}\n\nfunction formatNode(node: NodeDeclaration): string {\n return printSchemaDocument({ kind: \"Document\", declarations: [node] }).trimEnd();\n}\n\n/** Index of the `//` that starts a comment on `line`, ignoring `//` inside strings. */\nfunction commentStart(line: string): number {\n let inString = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n } else if (c === '\"') inString = true;\n else if (c === \"/\" && line[i + 1] === \"/\") return i;\n }\n return -1;\n}\n\ntype Block = { name: string; open: number; close: number };\n\n/** Top-level `node Name { … }` blocks with the offsets of their braces. */\nfunction nodeBlocks(source: string): Block[] {\n const blocks: Block[] = [];\n let depth = 0;\n let pending: { name: string } | null = null;\n let current: { name: string; open: number } | null = null;\n for (let i = 0; i < source.length; i++) {\n const c = source[i]!;\n if (c === \"/\" && source[i + 1] === \"/\") {\n while (i < source.length && source[i] !== \"\\n\") i++;\n continue;\n }\n if (c === '\"') {\n for (i++; i < source.length && source[i] !== '\"'; i++) if (source[i] === \"\\\\\") i++;\n continue;\n }\n if (depth === 0 && /[A-Za-z_]/.test(c) && (i === 0 || !/[A-Za-z0-9_]/.test(source[i - 1]!))) {\n const m = /^(node|relationship)\\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(source.slice(i));\n if (m) {\n pending = m[1] === \"node\" ? { name: m[2]! } : null;\n i += m[0].length - 1;\n continue;\n }\n }\n if (c === \"{\") {\n if (depth === 0 && pending) current = { name: pending.name, open: i };\n pending = null;\n depth++;\n } else if (c === \"}\") {\n depth--;\n if (depth === 0 && current) {\n blocks.push({ ...current, close: i });\n current = null;\n }\n }\n }\n return blocks;\n}\n\n/**\n * Merge the fields of `auth` into the existing block of the same node, or return `null` when\n * the block's layout is unusual (several fields per line, …) and should be reprinted instead.\n */\nfunction mergeBlock(\n source: string,\n block: Block,\n existing: NodeDeclaration,\n auth: NodeDeclaration,\n): string | null {\n const body = source.slice(block.open + 1, block.close);\n const lines = body.split(\"\\n\");\n // The closing brace must sit on its own line so new fields can go right before it.\n if (lines.length < 2 || lines[lines.length - 1]!.trim() !== \"\") return null;\n const names: { line: number; name: string }[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const cut = commentStart(line);\n const code = (cut >= 0 ? line.slice(0, cut) : line).trim();\n if (i === 0 && code !== \"\") return null; // a field on the `node X {` line\n if (!code) continue;\n const m = /^([A-Za-z_][A-Za-z0-9_]*)/.exec(code);\n if (!m) return null;\n names.push({ line: i, name: m[1]! });\n }\n if (\n names.length !== existing.fields.length ||\n names.some((n, i) => n.name !== existing.fields[i]!.name)\n ) {\n return null;\n }\n\n const firstLine = names[0] ? lines[names[0].line]! : \" \";\n const indent = /^\\s*/.exec(firstLine)![0] || \" \";\n const added: string[] = [];\n for (const field of auth.fields) {\n const at = existing.fields.findIndex((f) => f.name === field.name);\n if (at < 0) {\n added.push(`${indent}${formatField(field)}`);\n continue;\n }\n if (formatField(existing.fields[at]!) === formatField(field)) continue;\n const lineNo = names[at]!.line;\n const line = lines[lineNo]!;\n const cut = commentStart(line);\n const comment = cut >= 0 ? ` ${line.slice(cut)}` : \"\";\n lines[lineNo] = `${/^\\s*/.exec(line)![0]}${formatField(field)}${comment}`;\n }\n lines.splice(lines.length - 1, 0, ...added);\n return lines.join(\"\\n\");\n}\n\n/**\n * The `.cyphra` source with the Better Auth nodes of `authDoc` added or updated.\n *\n * @param existing - Current contents of `schema.cyphra`, or `undefined` if there is none.\n * @param authDoc - Auth nodes derived from the Better Auth configuration.\n * @throws When the existing file does not parse, or the merged schema does not resolve.\n */\nexport function mergeAuthSchema(existing: string | undefined, authDoc: SchemaDocument): string {\n if (existing === undefined || existing.trim() === \"\") {\n return `${HEADER}\\n${printSchemaDocument(authDoc)}`;\n }\n const doc = parseSchema(existing);\n const blocks = nodeBlocks(existing);\n const edits: { start: number; end: number; text: string }[] = [];\n const appended: string[] = [];\n\n for (const decl of authDoc.declarations) {\n if (decl.kind !== \"Node\") continue;\n const current = doc.declarations.find(\n (d): d is NodeDeclaration => d.kind === \"Node\" && d.name === decl.name,\n );\n const block = blocks.find((b) => b.name === decl.name);\n if (!current || !block) {\n appended.push(formatNode(decl));\n continue;\n }\n const merged = mergeBlock(existing, block, current, decl);\n if (merged !== null) {\n edits.push({ start: block.open + 1, end: block.close, text: merged });\n continue;\n }\n // Unusual layout: reprint this node, keeping its non-auth fields after the auth ones.\n const extra = current.fields.filter((f) => !decl.fields.some((a) => a.name === f.name));\n const node: NodeDeclaration = { ...decl, fields: [...decl.fields, ...extra] };\n const start = existing.lastIndexOf(\"node\", block.open);\n edits.push({ start, end: block.close + 1, text: formatNode(node) });\n }\n\n let out = existing;\n for (const e of edits.sort((a, b) => b.start - a.start)) {\n out = out.slice(0, e.start) + e.text + out.slice(e.end);\n }\n if (appended.length) out = `${out.trimEnd()}\\n\\n${appended.join(\"\\n\\n\")}\\n`;\n\n try {\n resolveSchema(parseSchema(out));\n } catch (cause) {\n throw new Error(\n \"@cyphra/better-auth: merging the Better Auth models into your schema produced an invalid schema. Check for fields on auth nodes that clash with Better Auth fields.\",\n { cause },\n );\n }\n return out;\n}\n","/**\n * Derives a Cyphra schema from Better Auth's database schema (core models plus plugins).\n *\n * - Each Better Auth model becomes a node named after its database model name in PascalCase\n * (`user` → `User`, `user_custom` → `UserCustom`).\n * - A field with `references` (a foreign key such as `Session.userId`) is not stored as a\n * property. It becomes an edge `(User)-[:HAS_SESSION]->(Session)`, a to-one relation field on\n * the child (`user`) and a list field on the parent (`sessions`).\n *\n * @packageDocumentation\n */\n\nimport type { BetterAuthDBSchema, DBFieldAttribute } from \"better-auth/db\";\nimport {\n resolveSchema,\n type Decorator,\n type NodeDeclaration,\n type NodeField,\n type ScalarNodeField,\n type ScalarTypeName,\n type SchemaDocument,\n type SchemaModel,\n} from \"@cyphra/schema\";\nimport {\n assertIdentifier,\n edgeType,\n lowerFirst,\n pascalCase,\n plural,\n relationFieldName,\n} from \"./naming.js\";\n\n/** Mapping functions Better Auth provides to adapters (`getModelName`, `getFieldName`). */\nexport interface SchemaNaming {\n schema: BetterAuthDBSchema;\n /** Schema key (or custom model name) → database model name. */\n getModelName: (model: string) => string;\n /** Schema field → database field name. */\n getFieldName: (args: { model: string; field: string }) => string;\n}\n\nexport type OnDelete = \"no action\" | \"restrict\" | \"cascade\" | \"set null\" | \"set default\";\n\nexport interface ScalarMapping {\n readonly kind: \"scalar\";\n /** Database field name (the property key on the node). */\n readonly name: string;\n readonly type: ScalarTypeName;\n readonly list: boolean;\n /** Better Auth's `unique` / `index` flags. */\n readonly unique: boolean;\n readonly index: boolean;\n}\n\nexport interface ForeignKeyMapping {\n readonly kind: \"fk\";\n /** Database field name Better Auth reads and writes, e.g. `userId`. */\n readonly name: string;\n /** To-one relation field on the child node, e.g. `user`. */\n readonly relation: string;\n /** Schema key of the referenced model, e.g. `user`. */\n readonly parentKey: string;\n /** Database field name of the referenced field on the parent (usually `id`). */\n readonly refField: string;\n readonly relType: string;\n /** List relation field on the parent node, e.g. `sessions`. */\n readonly inverse: string;\n readonly onDelete: OnDelete;\n readonly unique: boolean;\n readonly index: boolean;\n readonly required: boolean;\n}\n\nexport type FieldMapping = ScalarMapping | ForeignKeyMapping;\n\nexport interface ModelMapping {\n /** Better Auth schema key, e.g. `user`. */\n readonly key: string;\n /** Database model name, e.g. `user` or `users` with `usePlural`. */\n readonly dbName: string;\n /** Cyphra node name and Neo4j label, e.g. `User`. */\n readonly node: string;\n /** ORM delegate key, e.g. `user` or `twoFactor`. */\n readonly delegate: string;\n /** Database name of the id field. */\n readonly idField: string;\n /** Every Better Auth field by database name (the id included, as a scalar). */\n readonly fields: ReadonlyMap<string, FieldMapping>;\n readonly foreignKeys: readonly ForeignKeyMapping[];\n}\n\nexport interface AuthGraph {\n /** By Better Auth schema key. */\n readonly models: ReadonlyMap<string, ModelMapping>;\n /** The auth nodes as a `.cyphra` document (used by `createSchema`). */\n readonly document: SchemaDocument;\n /** The resolved model the ORM runtime runs on. */\n readonly schema: SchemaModel;\n}\n\nfunction scalarType(attr: DBFieldAttribute): { type: ScalarTypeName; list: boolean } {\n const t = attr.type;\n if (Array.isArray(t)) return { type: \"String\", list: false }; // enum of string literals\n switch (t) {\n case \"string\":\n case \"json\":\n return { type: \"String\", list: false };\n case \"number\":\n return { type: \"Int\", list: false };\n case \"boolean\":\n return { type: \"Boolean\", list: false };\n case \"date\":\n return { type: \"DateTime\", list: false };\n case \"string[]\":\n return { type: \"String\", list: true };\n case \"number[]\":\n return { type: \"Int\", list: true };\n default:\n throw new Error(`@cyphra/better-auth: unsupported field type ${JSON.stringify(t)}.`);\n }\n}\n\nconst dec = (name: string, args: Decorator[\"args\"] = []): Decorator => ({ name, args });\n\nfunction relationDecorator(relType: string, direction: \"IN\" | \"OUT\"): Decorator {\n return dec(\"relationship\", [\n { key: \"type\", value: { kind: \"string\", value: relType } },\n { key: \"direction\", value: { kind: \"identifier\", value: direction } },\n ]);\n}\n\nfunction resolveModelKey(schema: BetterAuthDBSchema, model: string): string {\n if (schema[model]) return model;\n const found = Object.entries(schema).find(([, t]) => t.modelName === model);\n if (!found) throw new Error(`@cyphra/better-auth: unknown referenced model \"${model}\".`);\n return found[0];\n}\n\ntype PendingFk = {\n childKey: string;\n name: string;\n attr: DBFieldAttribute;\n parentKey: string;\n};\n\n/**\n * Build the auth graph (node mappings, `.cyphra` document and resolved schema model) for a\n * Better Auth configuration.\n */\nexport function deriveAuthGraph(naming: SchemaNaming): AuthGraph {\n const { schema, getModelName, getFieldName } = naming;\n const keys = Object.keys(schema).sort(\n (a, b) => (schema[a]!.order ?? Infinity) - (schema[b]!.order ?? Infinity),\n );\n\n const nodeOf = new Map<string, string>();\n for (const key of keys) {\n const node = assertIdentifier(pascalCase(getModelName(key)), \"model name\");\n if ([...nodeOf.values()].includes(node)) {\n throw new Error(`@cyphra/better-auth: two models map to the node name \"${node}\".`);\n }\n nodeOf.set(key, node);\n }\n\n // Pass 1: scalar fields and the list of foreign keys.\n const fieldsOf = new Map<string, { field: NodeField; fk?: PendingFk }[]>();\n const mappingsOf = new Map<string, Map<string, FieldMapping>>();\n const pending: PendingFk[] = [];\n for (const key of keys) {\n const idField = assertIdentifier(getFieldName({ model: key, field: \"id\" }), \"field name\");\n const fields: { field: NodeField; fk?: PendingFk }[] = [\n {\n field: {\n kind: \"Scalar\",\n name: idField,\n type: { name: \"String\", optional: false },\n decorators: [\n dec(\"id\"),\n dec(\"default\", [{ key: \"fn\", value: { kind: \"identifier\", value: \"cuid\" } }]),\n ],\n },\n },\n ];\n const mappings = new Map<string, FieldMapping>([\n [\n idField,\n { kind: \"scalar\", name: idField, type: \"String\", list: false, unique: true, index: false },\n ],\n ]);\n for (const [fieldKey, attr] of Object.entries(schema[key]!.fields)) {\n if (fieldKey === \"id\") continue;\n const name = assertIdentifier(getFieldName({ model: key, field: fieldKey }), \"field name\");\n if (attr.references) {\n const fk = {\n childKey: key,\n name,\n attr,\n parentKey: resolveModelKey(schema, attr.references.model),\n };\n pending.push(fk);\n fields.push({ field: null as unknown as NodeField, fk });\n continue;\n }\n const { type, list } = scalarType(attr);\n const decorators: Decorator[] = [];\n if (attr.unique && !list) decorators.push(dec(\"unique\"));\n else if (attr.index && !list) decorators.push(dec(\"index\"));\n const field: ScalarNodeField = {\n kind: \"Scalar\",\n name,\n type: {\n name: type,\n optional: list ? false : attr.required !== true,\n ...(list ? { list } : {}),\n },\n decorators,\n };\n fields.push({ field });\n mappings.set(name, {\n kind: \"scalar\",\n name,\n type,\n list,\n unique: attr.unique === true,\n index: attr.index === true,\n });\n }\n fieldsOf.set(key, fields);\n mappingsOf.set(key, mappings);\n }\n\n // Pass 2: foreign keys become relation fields on both ends.\n const taken = new Map<string, Set<string>>();\n for (const key of keys) {\n taken.set(\n key,\n new Set([\n ...mappingsOf.get(key)!.keys(),\n ...pending.filter((p) => p.childKey === key).map((p) => p.name),\n ]),\n );\n }\n const inverseFields = new Map<string, NodeField[]>(keys.map((k) => [k, []]));\n const foreignKeysOf = new Map<string, ForeignKeyMapping[]>(keys.map((k) => [k, []]));\n\n for (const fk of pending) {\n const childNode = nodeOf.get(fk.childKey)!;\n const childTaken = taken.get(fk.childKey)!;\n const siblings = pending.filter(\n (p) => p.childKey === fk.childKey && p.parentKey === fk.parentKey,\n );\n\n let relation = relationFieldName(fk.name);\n if (relation !== fk.name && childTaken.has(relation)) relation = fk.name;\n childTaken.delete(fk.name);\n childTaken.add(relation);\n\n const relType = siblings.length > 1 ? edgeType(childNode, relation) : edgeType(childNode);\n\n const parentTaken = taken.get(fk.parentKey)!;\n const base =\n siblings.length > 1\n ? `${relation}${pascalCase(plural(childNode))}`\n : plural(lowerFirst(childNode));\n let inverse = base;\n for (let i = 2; parentTaken.has(inverse); i++) inverse = `${base}${i}`;\n parentTaken.add(inverse);\n\n const required = fk.attr.required === true;\n const refField = getFieldName({ model: fk.parentKey, field: fk.attr.references!.field });\n const mapping: ForeignKeyMapping = {\n kind: \"fk\",\n name: fk.name,\n relation,\n parentKey: fk.parentKey,\n refField,\n relType,\n inverse,\n onDelete: fk.attr.references!.onDelete ?? \"cascade\",\n unique: fk.attr.unique === true,\n index: fk.attr.index === true,\n required,\n };\n mappingsOf.get(fk.childKey)!.set(fk.name, mapping);\n foreignKeysOf.get(fk.childKey)!.push(mapping);\n\n const slot = fieldsOf.get(fk.childKey)!.find((f) => f.fk === fk)!;\n slot.field = {\n kind: \"Relational\",\n name: relation,\n target: nodeOf.get(fk.parentKey)!,\n cardinality: \"one\",\n optional: !required,\n decorators: [relationDecorator(relType, \"IN\")],\n };\n inverseFields.get(fk.parentKey)!.push({\n kind: \"Relational\",\n name: inverse,\n target: childNode,\n cardinality: \"many\",\n optional: false,\n decorators: [relationDecorator(relType, \"OUT\")],\n });\n }\n\n const declarations: NodeDeclaration[] = keys.map((key) => ({\n kind: \"Node\",\n name: nodeOf.get(key)!,\n fields: [...fieldsOf.get(key)!.map((f) => f.field), ...inverseFields.get(key)!],\n }));\n const document: SchemaDocument = { kind: \"Document\", declarations };\n\n const models = new Map<string, ModelMapping>();\n for (const key of keys) {\n const node = nodeOf.get(key)!;\n models.set(key, {\n key,\n dbName: getModelName(key),\n node,\n delegate: lowerFirst(node),\n idField: getFieldName({ model: key, field: \"id\" }),\n fields: mappingsOf.get(key)!,\n foreignKeys: foreignKeysOf.get(key)!,\n });\n }\n return { models, document, schema: resolveSchema(document) };\n}\n","/** Name conversions between Better Auth model / field names and Cyphra schema names. */\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Split `user_custom`, `oneToOneTable`, `API-key` into lower-case words. */\nfunction words(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((w) => w.toLowerCase());\n}\n\nconst capitalize = (w: string) => w.charAt(0).toUpperCase() + w.slice(1);\n\n/** `user` → `User`, `user_custom` → `UserCustom`, `twoFactor` → `TwoFactor`. */\nexport function pascalCase(name: string): string {\n const out = words(name).map(capitalize).join(\"\");\n return /^[0-9]/.test(out) ? `_${out}` : out;\n}\n\n/** `TwoFactor` → `TWO_FACTOR`. */\nexport function upperSnake(name: string): string {\n return words(name)\n .map((w) => w.toUpperCase())\n .join(\"_\");\n}\n\n/** `TwoFactor` → `twoFactor`. */\nexport function lowerFirst(name: string): string {\n return name.charAt(0).toLowerCase() + name.slice(1);\n}\n\n/** English plural good enough for field names: `session` → `sessions`, `policy` → `policies`. */\nexport function plural(name: string): string {\n if (/[^aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`;\n if (/(s|x|z|ch|sh)$/i.test(name)) return `${name}es`;\n return `${name}s`;\n}\n\n/** Relationship type from a parent to a child node: `Session` → `HAS_SESSION`. */\nexport function edgeType(childNode: string, suffix?: string): string {\n const parts = [upperSnake(childNode), ...(suffix ? [upperSnake(suffix)] : [])].filter(Boolean);\n return `HAS_${parts.join(\"_\") || \"RELATED\"}`;\n}\n\n/**\n * Name of the to-one relation field that replaces a foreign key on the child:\n * `userId` → `user`, `organization_id` → `organization`, `inviterId` → `inviter`.\n * Returns the foreign-key name itself when there is no `Id` suffix to strip.\n */\nexport function relationFieldName(fkName: string): string {\n const m = /^(.+?)(?:_id|Id|ID)$/.exec(fkName);\n return m && m[1] ? m[1] : fkName;\n}\n\n/** Throw when `name` cannot be written as a `.cyphra` identifier. */\nexport function assertIdentifier(name: string, what: string): string {\n if (!IDENTIFIER.test(name)) {\n throw new Error(\n `@cyphra/better-auth: ${what} \"${name}\" is not a valid Cyphra identifier (letters, digits and _; must not start with a digit).`,\n );\n }\n return name;\n}\n","/**\n * Translates Better Auth's `where` clauses into Cyphra `where` objects.\n *\n * Foreign-key fields are edges, so a clause on `userId` becomes a relation filter on the related\n * node's referenced field: `{ user: { is: { id: value } } }`.\n */\n\nimport type { CleanedWhere } from \"better-auth/adapters\";\nimport type { FieldMapping, ModelMapping, ScalarMapping } from \"./schema.js\";\n\ntype Filter = Record<string, unknown>;\n\n/** Coerce values Better Auth may send as strings (e.g. from query params) to the field type. */\nexport function coerceScalar(field: ScalarMapping, value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n if (field.type === \"Int\" && /^-?\\d+$/.test(value)) return Number(value);\n if (field.type === \"Boolean\" && (value === \"true\" || value === \"false\")) return value === \"true\";\n return value;\n}\n\nexport function fieldOf(model: ModelMapping, field: string): FieldMapping {\n const f = model.fields.get(field);\n if (!f) throw new Error(`@cyphra/better-auth: unknown field \"${model.dbName}.${field}\".`);\n return f;\n}\n\n/**\n * The Cyphra filter for one clause on a scalar field (also used for the referenced field of a\n * foreign key), or `undefined` when the clause matches every row.\n */\nfunction scalarFilter(w: CleanedWhere, field: ScalarMapping): unknown {\n const coerce = (v: unknown) => coerceScalar(field, v);\n const isText = (v: unknown) =>\n typeof v === \"string\" || (Array.isArray(v) && v.every((x) => typeof x === \"string\"));\n const mode =\n w.mode === \"insensitive\" && field.type === \"String\" && !field.list && isText(w.value)\n ? { mode: \"insensitive\" }\n : {};\n const value = w.value;\n\n if (field.list) {\n if (w.operator === \"eq\")\n return Array.isArray(value) ? { equals: value.map(coerce) } : { has: coerce(value) };\n throw new Error(\n `@cyphra/better-auth: operator \"${w.operator}\" is not supported on list fields.`,\n );\n }\n\n switch (w.operator) {\n case \"eq\":\n return value === null ? null : { equals: coerce(value), ...mode };\n case \"ne\":\n return value === null ? { not: null } : { not: coerce(value), ...mode };\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n return { [w.operator]: coerce(value) };\n case \"in\":\n case \"not_in\": {\n const list = (Array.isArray(value) ? value : [value]).filter(\n (v) => v !== null && v !== undefined,\n );\n if (w.operator === \"not_in\" && list.length === 0) return undefined;\n return { [w.operator === \"in\" ? \"in\" : \"notIn\"]: list.map(coerce), ...mode };\n }\n case \"contains\":\n return { contains: String(value), ...mode };\n case \"starts_with\":\n return { startsWith: String(value), ...mode };\n case \"ends_with\":\n return { endsWith: String(value), ...mode };\n default:\n throw new Error(`@cyphra/better-auth: unsupported where operator \"${String(w.operator)}\".`);\n }\n}\n\n/** One Better Auth clause as a Cyphra `where` object (`{}` matches everything). */\nfunction clauseWhere(\n model: ModelMapping,\n w: CleanedWhere,\n parentOf: (key: string) => ModelMapping,\n): Filter {\n const field = fieldOf(model, w.field);\n if (field.kind === \"scalar\") {\n const f = scalarFilter(w, field);\n return f === undefined ? {} : { [field.name]: f };\n }\n // Foreign key → filter through the edge on the parent's referenced field.\n const parent = parentOf(field.parentKey);\n const ref = fieldOf(parent, field.refField);\n if (ref.kind !== \"scalar\")\n throw new Error(\"@cyphra/better-auth: references must target a scalar.\");\n if (w.value === null && w.operator === \"eq\") return { [field.relation]: null };\n if (w.value === null && w.operator === \"ne\") return { [field.relation]: { isNot: null } };\n const f = scalarFilter(w, ref);\n if (f === undefined) return {};\n return { [field.relation]: { is: { [ref.name]: f } } };\n}\n\n/**\n * Better Auth's connector semantics (same as its Prisma adapter): every `AND` clause must\n * hold, and at least one `OR` clause must hold when there are any.\n */\nexport function toCyphraWhere(\n model: ModelMapping,\n where: readonly CleanedWhere[] | undefined,\n parentOf: (key: string) => ModelMapping,\n): Filter {\n if (!where?.length) return {};\n const and = where.filter((w) => w.connector !== \"OR\").map((w) => clauseWhere(model, w, parentOf));\n const or = where.filter((w) => w.connector === \"OR\").map((w) => clauseWhere(model, w, parentOf));\n return {\n ...(and.length ? { AND: and } : {}),\n ...(or.length ? { OR: or } : {}),\n };\n}\n","import type { BetterAuthOptions } from \"better-auth/types\";\nimport { getAuthTables } from \"better-auth/db\";\nimport { initGetFieldName, initGetModelName } from \"better-auth/adapters\";\nimport { deriveAuthGraph, type AuthGraph } from \"./schema.js\";\n\n/** Naming options that must match the ones passed to `cyphraAdapter`. */\nexport interface AuthSchemaOptions {\n usePlural?: boolean;\n}\n\n/**\n * The Cyphra schema for a Better Auth configuration: the same one the adapter derives at\n * runtime. `document` is the `.cyphra` AST (print it with `printSchemaDocument`), `schema` the\n * resolved model (use it with `createOrm` or the migrator).\n *\n * @example\n * ```ts\n * import { constraintStatementsFromSchema } from \"@cyphra/migrator\";\n * const { document } = authSchema(auth.options);\n * constraintStatementsFromSchema(document); // CREATE CONSTRAINT … for User, Session, …\n * ```\n */\nexport function authSchema(options: BetterAuthOptions, naming: AuthSchemaOptions = {}): AuthGraph {\n const tables = getAuthTables(options);\n const usePlural = naming.usePlural ?? false;\n return deriveAuthGraph({\n schema: tables,\n getModelName: initGetModelName({ schema: tables, usePlural }),\n getFieldName: initGetFieldName({ schema: tables, usePlural }),\n });\n}\n","/**\n * Cypher that converts data written by `neo4j-better-auth` (0.x) to the layout this adapter\n * uses.\n *\n * | neo4j-better-auth | @cyphra/better-auth |\n * | ------------------------------------------- | ----------------------------------------- |\n * | label = database model name (`user`) | PascalCase label (`User`) |\n * | foreign key property + `HAS_*` edge | `HAS_*` edge only |\n * | dates as ISO strings | `DateTime` values |\n * | numbers as floats | integers (`Int`) |\n *\n * @packageDocumentation\n */\n\nimport type { BetterAuthOptions } from \"better-auth/types\";\nimport { authSchema, type AuthSchemaOptions } from \"./options.js\";\n\nfunction quote(id: string): string {\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n}\n\n/** neo4j-better-auth's relationship type for a child label (`session` → `HAS_SESSION`). */\nfunction legacyEdgeType(childLabel: string): string {\n const core = childLabel\n .replace(/[^a-zA-Z0-9]/g, \"_\")\n .toUpperCase()\n .replace(/_+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n return `HAS_${core || \"RELATED\"}`;\n}\n\n/** neo4j-better-auth's constraint / index names (`user_email_unique`, `session_userId_idx`). */\nfunction legacyObjectName(...parts: string[]): string {\n return quote(parts.join(\"_\").replace(/[^a-zA-Z0-9_]/g, \"_\"));\n}\n\n/**\n * Cypher statements, in order, that migrate a graph written by `neo4j-better-auth` for the\n * same Better Auth configuration. Run them once, then create the new constraints with\n * `cyphra migrate deploy` (or `cyphra db push`). Every statement is idempotent.\n *\n * Steps: drop the old constraints and indexes, relabel nodes, rebuild the `HAS_*` edges from the\n * foreign-key properties and remove those properties, convert ISO date strings to `datetime()`\n * and float numbers to integers.\n *\n * @param options - Your Better Auth options (plugins included).\n * @param naming - Must match the `usePlural` you used with neo4j-better-auth.\n */\nexport function neo4jBetterAuthMigration(\n options: BetterAuthOptions,\n naming: AuthSchemaOptions = {},\n): string[] {\n const graph = authSchema(options, naming);\n const models = [...graph.models.values()];\n const byKey = (key: string) => graph.models.get(key)!;\n const out: string[] = [];\n\n // 1. Old constraints and indexes (they target the old labels).\n for (const m of models) {\n out.push(`DROP CONSTRAINT ${legacyObjectName(m.dbName, \"id_unique\")} IF EXISTS`);\n for (const f of m.fields.values()) {\n if (f.name === m.idField) continue;\n if (f.unique)\n out.push(`DROP CONSTRAINT ${legacyObjectName(m.dbName, f.name, \"unique\")} IF EXISTS`);\n else if (f.index)\n out.push(`DROP INDEX ${legacyObjectName(m.dbName, f.name, \"idx\")} IF EXISTS`);\n }\n }\n\n // 2. Labels.\n for (const m of models) {\n if (m.dbName === m.node) continue;\n out.push(`MATCH (n:${quote(m.dbName)}) SET n:${quote(m.node)} REMOVE n:${quote(m.dbName)}`);\n }\n\n // 3. Edges from the foreign-key properties, then the old edge types that changed name.\n const removeOld: string[] = [];\n for (const m of models) {\n const child = quote(m.node);\n for (const fk of m.foreignKeys) {\n const parent = byKey(fk.parentKey);\n const prop = `c.${quote(fk.name)}`;\n out.push(\n `MATCH (c:${child}) WHERE ${prop} IS NOT NULL ` +\n `MATCH (p:${quote(parent.node)}) WHERE p.${quote(fk.refField)} = ${prop} ` +\n `MERGE (p)-[:${quote(fk.relType)}]->(c)`,\n );\n const oldType = legacyEdgeType(m.dbName);\n const newTypes = m.foreignKeys\n .filter((other) => other.parentKey === fk.parentKey)\n .map((other) => other.relType);\n if (!newTypes.includes(oldType)) {\n removeOld.push(\n `MATCH (:${quote(parent.node)})-[r:${quote(oldType)}]->(:${child}) DELETE r`,\n );\n }\n }\n }\n out.push(...new Set(removeOld));\n for (const m of models) {\n for (const fk of m.foreignKeys) {\n out.push(\n `MATCH (c:${quote(m.node)}) WHERE c.${quote(fk.name)} IS NOT NULL REMOVE c.${quote(fk.name)}`,\n );\n }\n }\n\n // 4. Value types.\n for (const m of models) {\n for (const f of m.fields.values()) {\n if (f.kind !== \"scalar\") continue;\n const p = `n.${quote(f.name)}`;\n const match = `MATCH (n:${quote(m.node)})`;\n if (f.type === \"DateTime\" && !f.list) {\n // toString(x) = x only holds for strings, so converted values are left alone.\n out.push(`${match} WHERE toString(${p}) = ${p} SET ${p} = datetime(${p})`);\n } else if (f.type === \"Int\" && !f.list) {\n out.push(`${match} WHERE ${p} IS NOT NULL SET ${p} = toInteger(${p})`);\n } else if (f.type === \"Int\" && f.list) {\n out.push(`${match} WHERE ${p} IS NOT NULL SET ${p} = [x IN ${p} | toInteger(x)]`);\n }\n }\n }\n return out;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OASK;AAEP,SAAS,iBAAoC;;;ACF7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAEP,IAAM,SAAS;AAAA;AAAA;AAAA;AAMf,SAAS,YAAY,OAA0B;AAC7C,QAAM,OAAO,oBAAoB;AAAA,IAC/B,MAAM;AAAA,IACN,cAAc,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,QAAQ,CAAC,KAAK,EAAE,CAAC;AAAA,EAC7D,CAAC;AACD,SAAO,KAAK,MAAM,IAAI,EAAE,CAAC,EAAG,KAAK;AACnC;AAEA,SAAS,WAAW,MAA+B;AACjD,SAAO,oBAAoB,EAAE,MAAM,YAAY,cAAc,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ;AACjF;AAGA,SAAS,aA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QAAQ;AACtB,eAAW,KAAK,EAAE,OAAO,OAAO,GAAG;AACjC,UAAI,EAAE,SAAS,SAAU;AACzB,YAAM,IAAI,KAAKA,OAAM,EAAE,IAAI,CAAC;AAC5B,YAAM,QAAQ,YAAYA,OAAM,EAAE,IAAI,CAAC;AACvC,UAAI,EAAE,SAAS,cAAc,CAAC,EAAE,MAAM;AAEpC,YAAI,KAAK,GAAG,KAAK,mBAAmB,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,GAAG;AAAA,MAC3E,WAAW,EAAE,SAAS,SAAS,CAAC,EAAE,MAAM;AACtC,YAAI,KAAK,GAAG,KAAK,UAAU,CAAC,oBAAoB,CAAC,gBAAgB,CAAC,GAAG;AAAA,MACvE,WAAW,EAAE,SAAS,SAAS,EAAE,MAAM;AACrC,YAAI,KAAK,GAAG,KAAK,UAAU,CAAC,oBAAoB,CAAC,YAAY,CAAC,kBAAkB;AAAA,MAClF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":["resolveSchema","resolveSchema","f","quote"]}
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@cyphra/better-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.0",
4
+ "description": "Better Auth database adapter for Neo4j, built on the Cyphra ORM: auth and business data in one typed graph",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "main": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "@cyphra/runtime": "0.4.0",
24
+ "@cyphra/schema": "0.4.0"
25
+ },
26
+ "peerDependencies": {
27
+ "better-auth": "^1.7.27"
28
+ },
29
+ "devDependencies": {
30
+ "@better-auth/core": "1.7.27",
31
+ "@better-auth/test-utils": "1.7.27",
32
+ "@neo4j/cypher-builder": "^3.3.0",
33
+ "@types/node": "^22.20.5",
34
+ "better-auth": "1.7.27",
35
+ "neo4j-better-auth": "0.2.1",
36
+ "neo4j-driver": "^5.28.3",
37
+ "tsup": "^8.5.1",
38
+ "typescript": "^5.9.3",
39
+ "vitest": "^4.1.12",
40
+ "@cyphra/migrator": "0.4.0"
41
+ },
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/Cyphra-dev/cyphra.git",
46
+ "directory": "packages/better-auth"
47
+ },
48
+ "homepage": "https://www.cyphra.dev/better-auth",
49
+ "bugs": {
50
+ "url": "https://github.com/Cyphra-dev/cyphra/issues"
51
+ },
52
+ "keywords": [
53
+ "better-auth",
54
+ "neo4j",
55
+ "auth",
56
+ "authentication",
57
+ "adapter",
58
+ "orm",
59
+ "typescript",
60
+ "cyphra",
61
+ "graph-database"
62
+ ],
63
+ "scripts": {
64
+ "build": "tsup",
65
+ "typecheck": "tsc --noEmit",
66
+ "test": "vitest run"
67
+ }
6
68
  }