@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.
package/dist/index.js ADDED
@@ -0,0 +1,937 @@
1
+ // src/adapter.ts
2
+ import {
3
+ createAdapterFactory
4
+ } from "better-auth/adapters";
5
+ import { createOrm } from "@cyphra/runtime";
6
+
7
+ // src/merge.ts
8
+ import {
9
+ parseSchema,
10
+ printSchemaDocument,
11
+ resolveSchema
12
+ } from "@cyphra/schema";
13
+ var HEADER = `// Better Auth models, written by @cyphra/better-auth (npx @better-auth/cli generate).
14
+ // You can add fields and relations to these nodes and add your own models: running the
15
+ // generator again updates the Better Auth fields and keeps the rest.
16
+ `;
17
+ function formatField(field) {
18
+ const text = printSchemaDocument({
19
+ kind: "Document",
20
+ declarations: [{ kind: "Node", name: "X", fields: [field] }]
21
+ });
22
+ return text.split("\n")[1].trim();
23
+ }
24
+ function formatNode(node) {
25
+ return printSchemaDocument({ kind: "Document", declarations: [node] }).trimEnd();
26
+ }
27
+ function commentStart(line) {
28
+ let inString = false;
29
+ for (let i = 0; i < line.length; i++) {
30
+ const c = line[i];
31
+ if (inString) {
32
+ if (c === "\\") i++;
33
+ else if (c === '"') inString = false;
34
+ } else if (c === '"') inString = true;
35
+ else if (c === "/" && line[i + 1] === "/") return i;
36
+ }
37
+ return -1;
38
+ }
39
+ function nodeBlocks(source) {
40
+ const blocks = [];
41
+ let depth = 0;
42
+ let pending = null;
43
+ let current = null;
44
+ for (let i = 0; i < source.length; i++) {
45
+ const c = source[i];
46
+ if (c === "/" && source[i + 1] === "/") {
47
+ while (i < source.length && source[i] !== "\n") i++;
48
+ continue;
49
+ }
50
+ if (c === '"') {
51
+ for (i++; i < source.length && source[i] !== '"'; i++) if (source[i] === "\\") i++;
52
+ continue;
53
+ }
54
+ if (depth === 0 && /[A-Za-z_]/.test(c) && (i === 0 || !/[A-Za-z0-9_]/.test(source[i - 1]))) {
55
+ const m = /^(node|relationship)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(source.slice(i));
56
+ if (m) {
57
+ pending = m[1] === "node" ? { name: m[2] } : null;
58
+ i += m[0].length - 1;
59
+ continue;
60
+ }
61
+ }
62
+ if (c === "{") {
63
+ if (depth === 0 && pending) current = { name: pending.name, open: i };
64
+ pending = null;
65
+ depth++;
66
+ } else if (c === "}") {
67
+ depth--;
68
+ if (depth === 0 && current) {
69
+ blocks.push({ ...current, close: i });
70
+ current = null;
71
+ }
72
+ }
73
+ }
74
+ return blocks;
75
+ }
76
+ function mergeBlock(source, block, existing, auth) {
77
+ const body = source.slice(block.open + 1, block.close);
78
+ const lines = body.split("\n");
79
+ if (lines.length < 2 || lines[lines.length - 1].trim() !== "") return null;
80
+ const names = [];
81
+ for (let i = 0; i < lines.length; i++) {
82
+ const line = lines[i];
83
+ const cut = commentStart(line);
84
+ const code = (cut >= 0 ? line.slice(0, cut) : line).trim();
85
+ if (i === 0 && code !== "") return null;
86
+ if (!code) continue;
87
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)/.exec(code);
88
+ if (!m) return null;
89
+ names.push({ line: i, name: m[1] });
90
+ }
91
+ if (names.length !== existing.fields.length || names.some((n, i) => n.name !== existing.fields[i].name)) {
92
+ return null;
93
+ }
94
+ const firstLine = names[0] ? lines[names[0].line] : " ";
95
+ const indent = /^\s*/.exec(firstLine)[0] || " ";
96
+ const added = [];
97
+ for (const field of auth.fields) {
98
+ const at = existing.fields.findIndex((f) => f.name === field.name);
99
+ if (at < 0) {
100
+ added.push(`${indent}${formatField(field)}`);
101
+ continue;
102
+ }
103
+ if (formatField(existing.fields[at]) === formatField(field)) continue;
104
+ const lineNo = names[at].line;
105
+ const line = lines[lineNo];
106
+ const cut = commentStart(line);
107
+ const comment = cut >= 0 ? ` ${line.slice(cut)}` : "";
108
+ lines[lineNo] = `${/^\s*/.exec(line)[0]}${formatField(field)}${comment}`;
109
+ }
110
+ lines.splice(lines.length - 1, 0, ...added);
111
+ return lines.join("\n");
112
+ }
113
+ function mergeAuthSchema(existing, authDoc) {
114
+ if (existing === void 0 || existing.trim() === "") {
115
+ return `${HEADER}
116
+ ${printSchemaDocument(authDoc)}`;
117
+ }
118
+ const doc = parseSchema(existing);
119
+ const blocks = nodeBlocks(existing);
120
+ const edits = [];
121
+ const appended = [];
122
+ for (const decl of authDoc.declarations) {
123
+ if (decl.kind !== "Node") continue;
124
+ const current = doc.declarations.find(
125
+ (d) => d.kind === "Node" && d.name === decl.name
126
+ );
127
+ const block = blocks.find((b) => b.name === decl.name);
128
+ if (!current || !block) {
129
+ appended.push(formatNode(decl));
130
+ continue;
131
+ }
132
+ const merged = mergeBlock(existing, block, current, decl);
133
+ if (merged !== null) {
134
+ edits.push({ start: block.open + 1, end: block.close, text: merged });
135
+ continue;
136
+ }
137
+ const extra = current.fields.filter((f) => !decl.fields.some((a) => a.name === f.name));
138
+ const node = { ...decl, fields: [...decl.fields, ...extra] };
139
+ const start = existing.lastIndexOf("node", block.open);
140
+ edits.push({ start, end: block.close + 1, text: formatNode(node) });
141
+ }
142
+ let out = existing;
143
+ for (const e of edits.sort((a, b) => b.start - a.start)) {
144
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
145
+ }
146
+ if (appended.length) out = `${out.trimEnd()}
147
+
148
+ ${appended.join("\n\n")}
149
+ `;
150
+ try {
151
+ resolveSchema(parseSchema(out));
152
+ } catch (cause) {
153
+ throw new Error(
154
+ "@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.",
155
+ { cause }
156
+ );
157
+ }
158
+ return out;
159
+ }
160
+
161
+ // src/schema.ts
162
+ import {
163
+ resolveSchema as resolveSchema2
164
+ } from "@cyphra/schema";
165
+
166
+ // src/naming.ts
167
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
168
+ function words(name) {
169
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w.toLowerCase());
170
+ }
171
+ var capitalize = (w) => w.charAt(0).toUpperCase() + w.slice(1);
172
+ function pascalCase(name) {
173
+ const out = words(name).map(capitalize).join("");
174
+ return /^[0-9]/.test(out) ? `_${out}` : out;
175
+ }
176
+ function upperSnake(name) {
177
+ return words(name).map((w) => w.toUpperCase()).join("_");
178
+ }
179
+ function lowerFirst(name) {
180
+ return name.charAt(0).toLowerCase() + name.slice(1);
181
+ }
182
+ function plural(name) {
183
+ if (/[^aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`;
184
+ if (/(s|x|z|ch|sh)$/i.test(name)) return `${name}es`;
185
+ return `${name}s`;
186
+ }
187
+ function edgeType(childNode, suffix) {
188
+ const parts = [upperSnake(childNode), ...suffix ? [upperSnake(suffix)] : []].filter(Boolean);
189
+ return `HAS_${parts.join("_") || "RELATED"}`;
190
+ }
191
+ function relationFieldName(fkName) {
192
+ const m = /^(.+?)(?:_id|Id|ID)$/.exec(fkName);
193
+ return m && m[1] ? m[1] : fkName;
194
+ }
195
+ function assertIdentifier(name, what) {
196
+ if (!IDENTIFIER.test(name)) {
197
+ throw new Error(
198
+ `@cyphra/better-auth: ${what} "${name}" is not a valid Cyphra identifier (letters, digits and _; must not start with a digit).`
199
+ );
200
+ }
201
+ return name;
202
+ }
203
+
204
+ // src/schema.ts
205
+ function scalarType(attr) {
206
+ const t = attr.type;
207
+ if (Array.isArray(t)) return { type: "String", list: false };
208
+ switch (t) {
209
+ case "string":
210
+ case "json":
211
+ return { type: "String", list: false };
212
+ case "number":
213
+ return { type: "Int", list: false };
214
+ case "boolean":
215
+ return { type: "Boolean", list: false };
216
+ case "date":
217
+ return { type: "DateTime", list: false };
218
+ case "string[]":
219
+ return { type: "String", list: true };
220
+ case "number[]":
221
+ return { type: "Int", list: true };
222
+ default:
223
+ throw new Error(`@cyphra/better-auth: unsupported field type ${JSON.stringify(t)}.`);
224
+ }
225
+ }
226
+ var dec = (name, args = []) => ({ name, args });
227
+ function relationDecorator(relType, direction) {
228
+ return dec("relationship", [
229
+ { key: "type", value: { kind: "string", value: relType } },
230
+ { key: "direction", value: { kind: "identifier", value: direction } }
231
+ ]);
232
+ }
233
+ function resolveModelKey(schema, model) {
234
+ if (schema[model]) return model;
235
+ const found = Object.entries(schema).find(([, t]) => t.modelName === model);
236
+ if (!found) throw new Error(`@cyphra/better-auth: unknown referenced model "${model}".`);
237
+ return found[0];
238
+ }
239
+ function deriveAuthGraph(naming) {
240
+ const { schema, getModelName, getFieldName } = naming;
241
+ const keys = Object.keys(schema).sort(
242
+ (a, b) => (schema[a].order ?? Infinity) - (schema[b].order ?? Infinity)
243
+ );
244
+ const nodeOf = /* @__PURE__ */ new Map();
245
+ for (const key of keys) {
246
+ const node = assertIdentifier(pascalCase(getModelName(key)), "model name");
247
+ if ([...nodeOf.values()].includes(node)) {
248
+ throw new Error(`@cyphra/better-auth: two models map to the node name "${node}".`);
249
+ }
250
+ nodeOf.set(key, node);
251
+ }
252
+ const fieldsOf = /* @__PURE__ */ new Map();
253
+ const mappingsOf = /* @__PURE__ */ new Map();
254
+ const pending = [];
255
+ for (const key of keys) {
256
+ const idField = assertIdentifier(getFieldName({ model: key, field: "id" }), "field name");
257
+ const fields = [
258
+ {
259
+ field: {
260
+ kind: "Scalar",
261
+ name: idField,
262
+ type: { name: "String", optional: false },
263
+ decorators: [
264
+ dec("id"),
265
+ dec("default", [{ key: "fn", value: { kind: "identifier", value: "cuid" } }])
266
+ ]
267
+ }
268
+ }
269
+ ];
270
+ const mappings = /* @__PURE__ */ new Map([
271
+ [
272
+ idField,
273
+ { kind: "scalar", name: idField, type: "String", list: false, unique: true, index: false }
274
+ ]
275
+ ]);
276
+ for (const [fieldKey, attr] of Object.entries(schema[key].fields)) {
277
+ if (fieldKey === "id") continue;
278
+ const name = assertIdentifier(getFieldName({ model: key, field: fieldKey }), "field name");
279
+ if (attr.references) {
280
+ const fk = {
281
+ childKey: key,
282
+ name,
283
+ attr,
284
+ parentKey: resolveModelKey(schema, attr.references.model)
285
+ };
286
+ pending.push(fk);
287
+ fields.push({ field: null, fk });
288
+ continue;
289
+ }
290
+ const { type, list } = scalarType(attr);
291
+ const decorators = [];
292
+ if (attr.unique && !list) decorators.push(dec("unique"));
293
+ else if (attr.index && !list) decorators.push(dec("index"));
294
+ const field = {
295
+ kind: "Scalar",
296
+ name,
297
+ type: {
298
+ name: type,
299
+ optional: list ? false : attr.required !== true,
300
+ ...list ? { list } : {}
301
+ },
302
+ decorators
303
+ };
304
+ fields.push({ field });
305
+ mappings.set(name, {
306
+ kind: "scalar",
307
+ name,
308
+ type,
309
+ list,
310
+ unique: attr.unique === true,
311
+ index: attr.index === true
312
+ });
313
+ }
314
+ fieldsOf.set(key, fields);
315
+ mappingsOf.set(key, mappings);
316
+ }
317
+ const taken = /* @__PURE__ */ new Map();
318
+ for (const key of keys) {
319
+ taken.set(
320
+ key,
321
+ /* @__PURE__ */ new Set([
322
+ ...mappingsOf.get(key).keys(),
323
+ ...pending.filter((p) => p.childKey === key).map((p) => p.name)
324
+ ])
325
+ );
326
+ }
327
+ const inverseFields = new Map(keys.map((k) => [k, []]));
328
+ const foreignKeysOf = new Map(keys.map((k) => [k, []]));
329
+ for (const fk of pending) {
330
+ const childNode = nodeOf.get(fk.childKey);
331
+ const childTaken = taken.get(fk.childKey);
332
+ const siblings = pending.filter(
333
+ (p) => p.childKey === fk.childKey && p.parentKey === fk.parentKey
334
+ );
335
+ let relation = relationFieldName(fk.name);
336
+ if (relation !== fk.name && childTaken.has(relation)) relation = fk.name;
337
+ childTaken.delete(fk.name);
338
+ childTaken.add(relation);
339
+ const relType = siblings.length > 1 ? edgeType(childNode, relation) : edgeType(childNode);
340
+ const parentTaken = taken.get(fk.parentKey);
341
+ const base = siblings.length > 1 ? `${relation}${pascalCase(plural(childNode))}` : plural(lowerFirst(childNode));
342
+ let inverse = base;
343
+ for (let i = 2; parentTaken.has(inverse); i++) inverse = `${base}${i}`;
344
+ parentTaken.add(inverse);
345
+ const required = fk.attr.required === true;
346
+ const refField = getFieldName({ model: fk.parentKey, field: fk.attr.references.field });
347
+ const mapping = {
348
+ kind: "fk",
349
+ name: fk.name,
350
+ relation,
351
+ parentKey: fk.parentKey,
352
+ refField,
353
+ relType,
354
+ inverse,
355
+ onDelete: fk.attr.references.onDelete ?? "cascade",
356
+ unique: fk.attr.unique === true,
357
+ index: fk.attr.index === true,
358
+ required
359
+ };
360
+ mappingsOf.get(fk.childKey).set(fk.name, mapping);
361
+ foreignKeysOf.get(fk.childKey).push(mapping);
362
+ const slot = fieldsOf.get(fk.childKey).find((f) => f.fk === fk);
363
+ slot.field = {
364
+ kind: "Relational",
365
+ name: relation,
366
+ target: nodeOf.get(fk.parentKey),
367
+ cardinality: "one",
368
+ optional: !required,
369
+ decorators: [relationDecorator(relType, "IN")]
370
+ };
371
+ inverseFields.get(fk.parentKey).push({
372
+ kind: "Relational",
373
+ name: inverse,
374
+ target: childNode,
375
+ cardinality: "many",
376
+ optional: false,
377
+ decorators: [relationDecorator(relType, "OUT")]
378
+ });
379
+ }
380
+ const declarations = keys.map((key) => ({
381
+ kind: "Node",
382
+ name: nodeOf.get(key),
383
+ fields: [...fieldsOf.get(key).map((f) => f.field), ...inverseFields.get(key)]
384
+ }));
385
+ const document = { kind: "Document", declarations };
386
+ const models = /* @__PURE__ */ new Map();
387
+ for (const key of keys) {
388
+ const node = nodeOf.get(key);
389
+ models.set(key, {
390
+ key,
391
+ dbName: getModelName(key),
392
+ node,
393
+ delegate: lowerFirst(node),
394
+ idField: getFieldName({ model: key, field: "id" }),
395
+ fields: mappingsOf.get(key),
396
+ foreignKeys: foreignKeysOf.get(key)
397
+ });
398
+ }
399
+ return { models, document, schema: resolveSchema2(document) };
400
+ }
401
+
402
+ // src/where.ts
403
+ function coerceScalar(field, value) {
404
+ if (typeof value !== "string") return value;
405
+ if (field.type === "Int" && /^-?\d+$/.test(value)) return Number(value);
406
+ if (field.type === "Boolean" && (value === "true" || value === "false")) return value === "true";
407
+ return value;
408
+ }
409
+ function fieldOf(model, field) {
410
+ const f = model.fields.get(field);
411
+ if (!f) throw new Error(`@cyphra/better-auth: unknown field "${model.dbName}.${field}".`);
412
+ return f;
413
+ }
414
+ function scalarFilter(w, field) {
415
+ const coerce = (v) => coerceScalar(field, v);
416
+ const isText = (v) => typeof v === "string" || Array.isArray(v) && v.every((x) => typeof x === "string");
417
+ const mode = w.mode === "insensitive" && field.type === "String" && !field.list && isText(w.value) ? { mode: "insensitive" } : {};
418
+ const value = w.value;
419
+ if (field.list) {
420
+ if (w.operator === "eq")
421
+ return Array.isArray(value) ? { equals: value.map(coerce) } : { has: coerce(value) };
422
+ throw new Error(
423
+ `@cyphra/better-auth: operator "${w.operator}" is not supported on list fields.`
424
+ );
425
+ }
426
+ switch (w.operator) {
427
+ case "eq":
428
+ return value === null ? null : { equals: coerce(value), ...mode };
429
+ case "ne":
430
+ return value === null ? { not: null } : { not: coerce(value), ...mode };
431
+ case "lt":
432
+ case "lte":
433
+ case "gt":
434
+ case "gte":
435
+ return { [w.operator]: coerce(value) };
436
+ case "in":
437
+ case "not_in": {
438
+ const list = (Array.isArray(value) ? value : [value]).filter(
439
+ (v) => v !== null && v !== void 0
440
+ );
441
+ if (w.operator === "not_in" && list.length === 0) return void 0;
442
+ return { [w.operator === "in" ? "in" : "notIn"]: list.map(coerce), ...mode };
443
+ }
444
+ case "contains":
445
+ return { contains: String(value), ...mode };
446
+ case "starts_with":
447
+ return { startsWith: String(value), ...mode };
448
+ case "ends_with":
449
+ return { endsWith: String(value), ...mode };
450
+ default:
451
+ throw new Error(`@cyphra/better-auth: unsupported where operator "${String(w.operator)}".`);
452
+ }
453
+ }
454
+ function clauseWhere(model, w, parentOf) {
455
+ const field = fieldOf(model, w.field);
456
+ if (field.kind === "scalar") {
457
+ const f2 = scalarFilter(w, field);
458
+ return f2 === void 0 ? {} : { [field.name]: f2 };
459
+ }
460
+ const parent = parentOf(field.parentKey);
461
+ const ref = fieldOf(parent, field.refField);
462
+ if (ref.kind !== "scalar")
463
+ throw new Error("@cyphra/better-auth: references must target a scalar.");
464
+ if (w.value === null && w.operator === "eq") return { [field.relation]: null };
465
+ if (w.value === null && w.operator === "ne") return { [field.relation]: { isNot: null } };
466
+ const f = scalarFilter(w, ref);
467
+ if (f === void 0) return {};
468
+ return { [field.relation]: { is: { [ref.name]: f } } };
469
+ }
470
+ function toCyphraWhere(model, where, parentOf) {
471
+ if (!where?.length) return {};
472
+ const and = where.filter((w) => w.connector !== "OR").map((w) => clauseWhere(model, w, parentOf));
473
+ const or = where.filter((w) => w.connector === "OR").map((w) => clauseWhere(model, w, parentOf));
474
+ return {
475
+ ...and.length ? { AND: and } : {},
476
+ ...or.length ? { OR: or } : {}
477
+ };
478
+ }
479
+
480
+ // src/adapter.ts
481
+ var LOCK_FLAG = "__cyphraLock";
482
+ function quote(id) {
483
+ return "`" + id.replace(/`/g, "``") + "`";
484
+ }
485
+ async function lockNode(db, node, field, value) {
486
+ const head = `MATCH (n:${quote(node)}) WHERE n.${quote(field)} = `;
487
+ const flag = `n.${quote(LOCK_FLAG)}`;
488
+ const tail = ` SET ${flag} = true REMOVE ${flag} RETURN count(n) AS c`;
489
+ const strings = Object.assign([head, tail], { raw: [head, tail] });
490
+ await db.$cypher(strings, value);
491
+ }
492
+ function fail(message) {
493
+ throw new Error(`@cyphra/better-auth: ${message}`);
494
+ }
495
+ function createOperations(source, onInit) {
496
+ return (ctx) => {
497
+ const graph = deriveAuthGraph(ctx);
498
+ const src = source(graph);
499
+ onInit?.(graph, src);
500
+ const modelOf = (model, modelKey) => graph.models.get(modelKey ?? ctx.getDefaultModelName(model)) ?? fail(`unknown model "${model}".`);
501
+ const parentOf = (key) => graph.models.get(key);
502
+ const delegate = (db, m) => db[m.delegate];
503
+ const whereOf = (m, where) => toCyphraWhere(m, where, parentOf);
504
+ const childrenOf = (m) => [...graph.models.values()].flatMap(
505
+ (c) => c.foreignKeys.filter((fk) => fk.parentKey === m.key).map((fk) => ({ child: c, fk }))
506
+ );
507
+ const selected = (m, select) => select?.length ? select.map((s) => m.fields.has(s) ? s : ctx.getFieldName({ model: m.key, field: s })) : [...m.fields.keys()];
508
+ function selectOf(m, select) {
509
+ const out = {};
510
+ for (const name of selected(m, select)) {
511
+ const f = fieldOf(m, name);
512
+ if (f.kind === "scalar") out[name] = true;
513
+ else out[f.relation] = { select: { [f.refField]: true } };
514
+ }
515
+ return out;
516
+ }
517
+ function toRow(m, rec, select) {
518
+ const out = {};
519
+ for (const name of selected(m, select)) {
520
+ const f = fieldOf(m, name);
521
+ if (f.kind === "scalar") out[name] = rec[name] ?? null;
522
+ else out[name] = rec[f.relation]?.[f.refField] ?? null;
523
+ }
524
+ return out;
525
+ }
526
+ function writeData(m, data, mode) {
527
+ const out = {};
528
+ for (const [key, value] of Object.entries(data)) {
529
+ if (value === void 0) continue;
530
+ const f = fieldOf(m, key);
531
+ if (f.kind === "scalar") out[key] = coerceScalar(f, value);
532
+ else if (value !== null) out[f.relation] = { connect: { [f.refField]: value } };
533
+ else if (mode === "update") out[f.relation] = { disconnect: true };
534
+ }
535
+ return out;
536
+ }
537
+ async function assertUniqueForeignKeys(tx, m, data, selfId) {
538
+ for (const fk of m.foreignKeys) {
539
+ const value = data[fk.name];
540
+ if (!fk.unique || value === void 0 || value === null) continue;
541
+ const parent = parentOf(fk.parentKey);
542
+ await lockNode(tx, parent.node, fk.refField, value);
543
+ const where = { [fk.relation]: { is: { [fk.refField]: value } } };
544
+ if (selfId !== void 0) where[m.idField] = { not: selfId };
545
+ if (await delegate(tx, m).count({ where }) > 0) {
546
+ fail(`unique constraint failed on ${m.dbName}.${fk.name} = ${JSON.stringify(value)}.`);
547
+ }
548
+ }
549
+ }
550
+ async function deleteWhere(tx, m, where, lineage = /* @__PURE__ */ new Set()) {
551
+ const next = /* @__PURE__ */ new Set([...lineage, m.key]);
552
+ for (const { child, fk } of childrenOf(m)) {
553
+ const childWhere = { [fk.relation]: { is: where } };
554
+ if (fk.onDelete === "restrict" || fk.onDelete === "no action") {
555
+ if (await delegate(tx, child).count({ where: childWhere }) > 0) {
556
+ fail(
557
+ `cannot delete ${m.dbName}: ${child.dbName}.${fk.name} references it (onDelete: "${fk.onDelete}").`
558
+ );
559
+ }
560
+ } else if (fk.onDelete === "cascade" && !lineage.has(child.key)) {
561
+ await deleteWhere(tx, child, childWhere, next);
562
+ }
563
+ }
564
+ return (await delegate(tx, m).deleteMany({ where })).count;
565
+ }
566
+ async function lockOne(tx, m, where) {
567
+ const first = await delegate(tx, m).findFirst({ where, select: { [m.idField]: true } });
568
+ if (!first) return null;
569
+ const id = first[m.idField];
570
+ await lockNode(tx, m.node, m.idField, id);
571
+ const still = await delegate(tx, m).count({ where: { AND: [where, { [m.idField]: id }] } });
572
+ return still === 1 ? id : null;
573
+ }
574
+ function joinPlan(m, join) {
575
+ const select = {};
576
+ const readers = [];
577
+ for (const [name, cfg] of Object.entries(join ?? {})) {
578
+ const jm = modelOf(name, cfg.modelKey);
579
+ const forward = jm.foreignKeys.find(
580
+ (fk) => fk.parentKey === m.key && fk.name === cfg.on.to
581
+ );
582
+ const backward = m.foreignKeys.find(
583
+ (fk) => fk.parentKey === jm.key && fk.name === cfg.on.from
584
+ );
585
+ const field = forward?.inverse ?? backward?.relation;
586
+ if (!field) continue;
587
+ const many = Boolean(forward);
588
+ select[field] = {
589
+ select: selectOf(jm),
590
+ ...many && cfg.limit !== void 0 ? { take: cfg.limit } : {}
591
+ };
592
+ readers.push((rec, out) => {
593
+ const v = rec[field];
594
+ const rows = (many ? v : v ? [v] : []).map((r) => toRow(jm, r));
595
+ out[name] = cfg.relation === "one-to-one" ? rows[0] ?? null : rows;
596
+ });
597
+ }
598
+ return {
599
+ select,
600
+ read: (rec, out) => {
601
+ for (const r of readers) r(rec, out);
602
+ return out;
603
+ }
604
+ };
605
+ }
606
+ function orderByOf(m, sortBy) {
607
+ if (!sortBy) return void 0;
608
+ const f = fieldOf(m, sortBy.field);
609
+ if (f.kind !== "scalar")
610
+ fail(`sorting by the foreign key ${m.dbName}.${f.name} is not supported.`);
611
+ return { [f.name]: sortBy.direction };
612
+ }
613
+ const adapter = {
614
+ create: async ({ model, modelKey, data, select }) => {
615
+ const m = modelOf(model, modelKey);
616
+ return src.write(async (tx) => {
617
+ await assertUniqueForeignKeys(tx, m, data, void 0);
618
+ const rec = await delegate(tx, m).create({
619
+ data: writeData(m, data, "create"),
620
+ select: selectOf(m)
621
+ });
622
+ return toRow(m, rec, select);
623
+ });
624
+ },
625
+ findOne: async ({
626
+ model,
627
+ modelKey,
628
+ where,
629
+ select,
630
+ join
631
+ }) => {
632
+ const m = modelOf(model, modelKey);
633
+ const plan = joinPlan(m, join);
634
+ const rec = await delegate(src.db, m).findFirst({
635
+ where: whereOf(m, where),
636
+ select: { ...selectOf(m, select), ...plan.select }
637
+ });
638
+ return rec ? plan.read(rec, toRow(m, rec, select)) : null;
639
+ },
640
+ findMany: async ({
641
+ model,
642
+ modelKey,
643
+ where,
644
+ limit,
645
+ sortBy,
646
+ offset,
647
+ select,
648
+ join
649
+ }) => {
650
+ const m = modelOf(model, modelKey);
651
+ const plan = joinPlan(m, join);
652
+ const recs = await delegate(src.db, m).findMany({
653
+ where: whereOf(m, where),
654
+ select: { ...selectOf(m, select), ...plan.select },
655
+ orderBy: orderByOf(m, sortBy),
656
+ ...offset ? { skip: offset } : {},
657
+ ...limit !== void 0 && limit >= 0 ? { take: limit } : {}
658
+ });
659
+ return recs.map((rec) => plan.read(rec, toRow(m, rec, select)));
660
+ },
661
+ count: async ({ model, modelKey, where }) => {
662
+ const m = modelOf(model, modelKey);
663
+ return delegate(src.db, m).count({ where: whereOf(m, where) });
664
+ },
665
+ update: async ({
666
+ model,
667
+ modelKey,
668
+ where,
669
+ update
670
+ }) => {
671
+ if (!where.length) return null;
672
+ const m = modelOf(model, modelKey);
673
+ return src.write(async (tx) => {
674
+ const first = await delegate(tx, m).findFirst({
675
+ where: whereOf(m, where),
676
+ select: { [m.idField]: true }
677
+ });
678
+ if (!first) return null;
679
+ const id = first[m.idField];
680
+ await assertUniqueForeignKeys(tx, m, update, id);
681
+ const rec = await delegate(tx, m).update({
682
+ where: { [m.idField]: id },
683
+ data: writeData(m, update, "update"),
684
+ select: selectOf(m)
685
+ });
686
+ return toRow(m, rec);
687
+ });
688
+ },
689
+ updateMany: async ({ model, modelKey, where, update }) => {
690
+ const m = modelOf(model, modelKey);
691
+ const data = writeData(m, update, "update");
692
+ const touchesEdges = m.foreignKeys.some((fk) => update[fk.name] !== void 0);
693
+ if (!touchesEdges) {
694
+ return (await delegate(src.db, m).updateMany({ where: whereOf(m, where), data })).count;
695
+ }
696
+ return src.write(async (tx) => {
697
+ const ids = await delegate(tx, m).findMany({
698
+ where: whereOf(m, where),
699
+ select: { [m.idField]: true }
700
+ });
701
+ for (const rec of ids) {
702
+ await assertUniqueForeignKeys(tx, m, update, rec[m.idField]);
703
+ await delegate(tx, m).update({ where: { [m.idField]: rec[m.idField] }, data });
704
+ }
705
+ return ids.length;
706
+ });
707
+ },
708
+ delete: async ({ model, modelKey, where }) => {
709
+ const m = modelOf(model, modelKey);
710
+ await src.write((tx) => deleteWhere(tx, m, whereOf(m, where)));
711
+ },
712
+ deleteMany: async ({ model, modelKey, where }) => {
713
+ const m = modelOf(model, modelKey);
714
+ return src.write((tx) => deleteWhere(tx, m, whereOf(m, where)));
715
+ },
716
+ /**
717
+ * Atomic find-and-delete of one row: lock it, re-check the predicate, delete it. Of N
718
+ * concurrent callers on the same row, one gets the row and the others get `null`.
719
+ */
720
+ consumeOne: async ({
721
+ model,
722
+ modelKey,
723
+ where
724
+ }) => {
725
+ const m = modelOf(model, modelKey);
726
+ return src.write(async (tx) => {
727
+ const id = await lockOne(tx, m, whereOf(m, where));
728
+ if (id === null) return null;
729
+ const byId = { [m.idField]: id };
730
+ const rec = await delegate(tx, m).findFirst({ where: byId, select: selectOf(m) });
731
+ if (!rec) return null;
732
+ await deleteWhere(tx, m, byId);
733
+ return toRow(m, rec);
734
+ });
735
+ },
736
+ /** Guarded atomic counter update on one row (`where` is both selector and guard). */
737
+ incrementOne: async ({
738
+ model,
739
+ modelKey,
740
+ where,
741
+ increment,
742
+ set
743
+ }) => {
744
+ const m = modelOf(model, modelKey);
745
+ return src.write(async (tx) => {
746
+ const id = await lockOne(tx, m, whereOf(m, where));
747
+ if (id === null) return null;
748
+ const data = writeData(m, set ?? {}, "update");
749
+ for (const [key, delta] of Object.entries(increment)) {
750
+ const f = fieldOf(m, key);
751
+ if (f.kind !== "scalar") fail(`cannot increment the foreign key ${m.dbName}.${key}.`);
752
+ data[key] = { increment: delta };
753
+ }
754
+ await assertUniqueForeignKeys(tx, m, set ?? {}, id);
755
+ const rec = await delegate(tx, m).update({
756
+ where: { [m.idField]: id },
757
+ data,
758
+ select: selectOf(m)
759
+ });
760
+ return toRow(m, rec);
761
+ });
762
+ },
763
+ createSchema: async ({ file, tables }) => {
764
+ const authGraph = deriveAuthGraph({
765
+ schema: tables,
766
+ getModelName: ctx.getModelName,
767
+ getFieldName: ctx.getFieldName
768
+ });
769
+ const { readFile } = await import("fs/promises");
770
+ const path = await import("path");
771
+ const target = file ?? await configuredSchemaPath(readFile) ?? "schema.cyphra";
772
+ let existing;
773
+ try {
774
+ existing = await readFile(path.resolve(process.cwd(), target), "utf8");
775
+ } catch (e) {
776
+ if (e.code !== "ENOENT") throw e;
777
+ }
778
+ return {
779
+ code: mergeAuthSchema(existing, authGraph.document),
780
+ path: target,
781
+ overwrite: true
782
+ };
783
+ }
784
+ };
785
+ return adapter;
786
+ };
787
+ }
788
+ async function configuredSchemaPath(readFile) {
789
+ try {
790
+ const config = JSON.parse(await readFile("cyphra.json", "utf8"));
791
+ return typeof config.schema === "string" ? config.schema : void 0;
792
+ } catch {
793
+ return void 0;
794
+ }
795
+ }
796
+ function cyphraAdapter(config) {
797
+ const client = config.client ?? config.db?.$client;
798
+ if (!client) fail("pass `client` (a CyphraClient) or `db` (a Cyphra ORM client).");
799
+ let resolvedOptions;
800
+ let root;
801
+ const base = {
802
+ adapterId: "cyphra",
803
+ adapterName: "Cyphra (Neo4j)",
804
+ usePlural: config.usePlural ?? false,
805
+ debugLogs: config.debugLogs ?? false,
806
+ supportsJSON: false,
807
+ supportsDates: true,
808
+ supportsBooleans: true,
809
+ supportsArrays: true,
810
+ supportsNumericIds: false,
811
+ supportsUUIDs: false
812
+ };
813
+ const factoryConfig = {
814
+ ...base,
815
+ transaction: (callback) => {
816
+ if (!resolvedOptions || !root) fail("adapter used before Better Auth initialized it.");
817
+ const options = resolvedOptions;
818
+ return root.source.write((tx) => {
819
+ const inTx = createAdapterFactory({
820
+ config: { ...base, transaction: false },
821
+ adapter: createOperations(() => ({ db: tx, write: (fn) => fn(tx) }))
822
+ });
823
+ return callback(inTx(options));
824
+ });
825
+ }
826
+ };
827
+ const factory = createAdapterFactory({
828
+ config: factoryConfig,
829
+ adapter: createOperations(
830
+ (graph) => {
831
+ const orm = createOrm(graph.schema, { client });
832
+ return { db: orm, write: (fn) => orm.$transaction(fn) };
833
+ },
834
+ (graph, source) => {
835
+ root = { graph, source };
836
+ }
837
+ )
838
+ });
839
+ return (options) => {
840
+ resolvedOptions = options;
841
+ return factory(options);
842
+ };
843
+ }
844
+
845
+ // src/options.ts
846
+ import { getAuthTables } from "better-auth/db";
847
+ import { initGetFieldName, initGetModelName } from "better-auth/adapters";
848
+ function authSchema(options, naming = {}) {
849
+ const tables = getAuthTables(options);
850
+ const usePlural = naming.usePlural ?? false;
851
+ return deriveAuthGraph({
852
+ schema: tables,
853
+ getModelName: initGetModelName({ schema: tables, usePlural }),
854
+ getFieldName: initGetFieldName({ schema: tables, usePlural })
855
+ });
856
+ }
857
+
858
+ // src/legacy.ts
859
+ function quote2(id) {
860
+ return "`" + id.replace(/`/g, "``") + "`";
861
+ }
862
+ function legacyEdgeType(childLabel) {
863
+ const core = childLabel.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase().replace(/_+/g, "_").replace(/^_|_$/g, "");
864
+ return `HAS_${core || "RELATED"}`;
865
+ }
866
+ function legacyObjectName(...parts) {
867
+ return quote2(parts.join("_").replace(/[^a-zA-Z0-9_]/g, "_"));
868
+ }
869
+ function neo4jBetterAuthMigration(options, naming = {}) {
870
+ const graph = authSchema(options, naming);
871
+ const models = [...graph.models.values()];
872
+ const byKey = (key) => graph.models.get(key);
873
+ const out = [];
874
+ for (const m of models) {
875
+ out.push(`DROP CONSTRAINT ${legacyObjectName(m.dbName, "id_unique")} IF EXISTS`);
876
+ for (const f of m.fields.values()) {
877
+ if (f.name === m.idField) continue;
878
+ if (f.unique)
879
+ out.push(`DROP CONSTRAINT ${legacyObjectName(m.dbName, f.name, "unique")} IF EXISTS`);
880
+ else if (f.index)
881
+ out.push(`DROP INDEX ${legacyObjectName(m.dbName, f.name, "idx")} IF EXISTS`);
882
+ }
883
+ }
884
+ for (const m of models) {
885
+ if (m.dbName === m.node) continue;
886
+ out.push(`MATCH (n:${quote2(m.dbName)}) SET n:${quote2(m.node)} REMOVE n:${quote2(m.dbName)}`);
887
+ }
888
+ const removeOld = [];
889
+ for (const m of models) {
890
+ const child = quote2(m.node);
891
+ for (const fk of m.foreignKeys) {
892
+ const parent = byKey(fk.parentKey);
893
+ const prop = `c.${quote2(fk.name)}`;
894
+ out.push(
895
+ `MATCH (c:${child}) WHERE ${prop} IS NOT NULL MATCH (p:${quote2(parent.node)}) WHERE p.${quote2(fk.refField)} = ${prop} MERGE (p)-[:${quote2(fk.relType)}]->(c)`
896
+ );
897
+ const oldType = legacyEdgeType(m.dbName);
898
+ const newTypes = m.foreignKeys.filter((other) => other.parentKey === fk.parentKey).map((other) => other.relType);
899
+ if (!newTypes.includes(oldType)) {
900
+ removeOld.push(
901
+ `MATCH (:${quote2(parent.node)})-[r:${quote2(oldType)}]->(:${child}) DELETE r`
902
+ );
903
+ }
904
+ }
905
+ }
906
+ out.push(...new Set(removeOld));
907
+ for (const m of models) {
908
+ for (const fk of m.foreignKeys) {
909
+ out.push(
910
+ `MATCH (c:${quote2(m.node)}) WHERE c.${quote2(fk.name)} IS NOT NULL REMOVE c.${quote2(fk.name)}`
911
+ );
912
+ }
913
+ }
914
+ for (const m of models) {
915
+ for (const f of m.fields.values()) {
916
+ if (f.kind !== "scalar") continue;
917
+ const p = `n.${quote2(f.name)}`;
918
+ const match = `MATCH (n:${quote2(m.node)})`;
919
+ if (f.type === "DateTime" && !f.list) {
920
+ out.push(`${match} WHERE toString(${p}) = ${p} SET ${p} = datetime(${p})`);
921
+ } else if (f.type === "Int" && !f.list) {
922
+ out.push(`${match} WHERE ${p} IS NOT NULL SET ${p} = toInteger(${p})`);
923
+ } else if (f.type === "Int" && f.list) {
924
+ out.push(`${match} WHERE ${p} IS NOT NULL SET ${p} = [x IN ${p} | toInteger(x)]`);
925
+ }
926
+ }
927
+ }
928
+ return out;
929
+ }
930
+ export {
931
+ authSchema,
932
+ cyphraAdapter,
933
+ deriveAuthGraph,
934
+ mergeAuthSchema,
935
+ neo4jBetterAuthMigration
936
+ };
937
+ //# sourceMappingURL=index.js.map