symmetria 3.7.0 → 4.0.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.
Files changed (78) hide show
  1. package/README.md +23 -7
  2. package/dist/better-auth.js +87 -45
  3. package/dist/better-auth.js.map +1 -1
  4. package/dist/{binding-evmthxTh.js → binding-B89OT4WU.js} +27 -11
  5. package/dist/binding-B89OT4WU.js.map +1 -0
  6. package/dist/bun.d.ts +2 -2
  7. package/dist/bun.js +33 -18
  8. package/dist/bun.js.map +1 -1
  9. package/dist/cohere.d.ts +4 -4
  10. package/dist/cohere.js +1 -1
  11. package/dist/{compile-tTAzzMes.js → compile-utszVqlQ.js} +91 -16
  12. package/dist/compile-utszVqlQ.js.map +1 -0
  13. package/dist/{core-DL4rAoIx.js → core-Bx7AWNTv.js} +172 -19
  14. package/dist/core-Bx7AWNTv.js.map +1 -0
  15. package/dist/driver.d.ts +3 -3
  16. package/dist/driver.js +2 -2
  17. package/dist/{errors-CLFkJWgJ.js → errors-B8ZYiXDf.js} +63 -2
  18. package/dist/errors-B8ZYiXDf.js.map +1 -0
  19. package/dist/google.d.ts +3 -3
  20. package/dist/google.js +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +244 -48
  23. package/dist/index.js.map +1 -1
  24. package/dist/{inspection-lTMOK6ty.js → inspection-BMEOg_IW.js} +4 -4
  25. package/dist/{inspection-lTMOK6ty.js.map → inspection-BMEOg_IW.js.map} +1 -1
  26. package/dist/internal.d.ts +2 -2
  27. package/dist/internal.js +5 -5
  28. package/dist/jina.d.ts +3 -3
  29. package/dist/jina.js +1 -1
  30. package/dist/{metadata-kSK6_Ygx.js → metadata-BK8xrwQz.js} +2 -2
  31. package/dist/{metadata-kSK6_Ygx.js.map → metadata-BK8xrwQz.js.map} +1 -1
  32. package/dist/mistral.d.ts +3 -3
  33. package/dist/mistral.js +1 -1
  34. package/dist/ollama.d.ts +2 -2
  35. package/dist/ollama.js +1 -1
  36. package/dist/openai.d.ts +4 -4
  37. package/dist/openai.js +1 -1
  38. package/dist/opentelemetry.d.ts +1 -1
  39. package/dist/opentelemetry.js +4 -3
  40. package/dist/opentelemetry.js.map +1 -1
  41. package/dist/{pg-CWyQOkxm.js → pg-DEB7wHfm.js} +18 -14
  42. package/dist/pg-DEB7wHfm.js.map +1 -0
  43. package/dist/{pg-IXwZIFh2.d.ts → pg-uS_gbCrQ.d.ts} +3 -3
  44. package/dist/pg.d.ts +3 -3
  45. package/dist/pg.js +2 -2
  46. package/dist/{pool-CEeO5spd.js → pool-Cx_3yB-c.js} +20 -10
  47. package/dist/pool-Cx_3yB-c.js.map +1 -0
  48. package/dist/{pool-wSI6eeqM.d.ts → pool-WwFrt_1y.d.ts} +2 -2
  49. package/dist/{profiling-CeH3c42X.js → profiling-EzaijUQ8.js} +23 -8
  50. package/dist/profiling-EzaijUQ8.js.map +1 -0
  51. package/dist/{search-g9i_87Fs.js → search--EcVHC_G.js} +7 -6
  52. package/dist/search--EcVHC_G.js.map +1 -0
  53. package/dist/{search-0TyudCVL.js → search-p560mO9o.js} +3 -3
  54. package/dist/{search-0TyudCVL.js.map → search-p560mO9o.js.map} +1 -1
  55. package/dist/search.d.ts +1 -1
  56. package/dist/search.js +1 -1
  57. package/dist/{table-Jb2bOypw.js → table-DftoF_WB.js} +8 -7
  58. package/dist/table-DftoF_WB.js.map +1 -0
  59. package/dist/{types-DNpNC7HQ.d.ts → types-BNXm3fZS.d.ts} +2770 -2700
  60. package/dist/{types-BKbG6MO1.js → types-Cy11hngx.js} +27 -2
  61. package/dist/types-Cy11hngx.js.map +1 -0
  62. package/dist/{values-CkYX-ZMl.js → values-DlbBU4PY.js} +2 -2
  63. package/dist/{values-CkYX-ZMl.js.map → values-DlbBU4PY.js.map} +1 -1
  64. package/dist/vector.d.ts +1 -1
  65. package/dist/vector.js +2 -2
  66. package/dist/voyage.d.ts +5 -5
  67. package/dist/voyage.js +1 -1
  68. package/package.json +1 -1
  69. package/dist/binding-evmthxTh.js.map +0 -1
  70. package/dist/compile-tTAzzMes.js.map +0 -1
  71. package/dist/core-DL4rAoIx.js.map +0 -1
  72. package/dist/errors-CLFkJWgJ.js.map +0 -1
  73. package/dist/pg-CWyQOkxm.js.map +0 -1
  74. package/dist/pool-CEeO5spd.js.map +0 -1
  75. package/dist/profiling-CeH3c42X.js.map +0 -1
  76. package/dist/search-g9i_87Fs.js.map +0 -1
  77. package/dist/table-Jb2bOypw.js.map +0 -1
  78. package/dist/types-BKbG6MO1.js.map +0 -1
package/README.md CHANGED
@@ -143,10 +143,16 @@ try {
143
143
 
144
144
  const authors = await db.users(({ name, posts }) => ({
145
145
  name,
146
- posts: posts(({ title, views }) => ({ title, views }), {
147
- orderBy: ({ id }) => id.descending,
148
- limit: 3,
149
- }),
146
+ posts: posts(
147
+ ({ title, views }) => ({
148
+ title,
149
+ views,
150
+ }),
151
+ {
152
+ orderBy: ({ id }) => id.descending,
153
+ limit: 3,
154
+ },
155
+ ),
150
156
  }));
151
157
  // { name: string; posts: { title: string; views: bigint }[] }[]
152
158
 
@@ -171,9 +177,15 @@ source and SQL tools.
171
177
 
172
178
  ```ts
173
179
  const feed = db.posts(
174
- ({ title, authorId }, { join }) => ({ title, author: join(authorId).name }),
175
- { orderBy: ({ id }) => id.descending },
180
+ ({ title, authorId }, { join }) => ({
181
+ title,
182
+ author: join(authorId).name,
183
+ }),
184
+ {
185
+ orderBy: ({ id }) => id.descending,
186
+ },
176
187
  );
188
+
177
189
  const page = feed({ limit: 10 });
178
190
  ```
179
191
 
@@ -198,7 +210,10 @@ Reusable projections bind to each source occurrence, including aliases and
198
210
  relations:
199
211
 
200
212
  ```ts
201
- const userCard = db.users.shape((user) => ({ name: user.name }));
213
+ const userCard = db.users.shape((user) => ({
214
+ name: user.name,
215
+ }));
216
+
202
217
  const feed = db.posts((post) => ({
203
218
  title: post.title,
204
219
  author: post.author(userCard),
@@ -260,6 +275,7 @@ const updated = await db.posts
260
275
  .returning("id", "views");
261
276
 
262
277
  const userCard = db.users.shape(({ id, name }) => ({ id, name }));
278
+
263
279
  await db.users.by
264
280
  .email("ada@example.com")
265
281
  .update({ name: "Ada Lovelace" })
@@ -1,7 +1,21 @@
1
- import { C as not, E as or, g as coalesce, m as and } from "./core-DL4rAoIx.js";
1
+ import { C as not, E as or, L as asText, g as coalesce, i as createExpression, m as and, z as COLUMN_EXPRESSION } from "./core-Bx7AWNTv.js";
2
2
  import { createAdapterFactory } from "better-auth/adapters";
3
3
  //#region src/entries/better-auth.ts
4
4
  const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
5
+ /** The operators that test equality, whose answer is the same on an enum and on its text. */
6
+ const EQUALITY = /* @__PURE__ */ new Set([
7
+ "eq",
8
+ "ne",
9
+ "in",
10
+ "not_in"
11
+ ]);
12
+ /**
13
+ * An enum column as its text. better-auth's own adapters keep a field declared
14
+ * as a list of literals in a text column, so it sorts and compares by spelling,
15
+ * not by the order the labels were declared in, and a value that is none of the
16
+ * labels matches no row where the enum itself would refuse it as an input.
17
+ */
18
+ const textOf = (column) => createExpression(asText(column[COLUMN_EXPRESSION]));
5
19
  /** `target[key]`, unless it is only what every object inherits (`constructor`). */
6
20
  const member = (target, key) => {
7
21
  const value = target[key];
@@ -28,12 +42,13 @@ const comparable = (type, value) => {
28
42
  };
29
43
  const none = (column) => column.in([]);
30
44
  const predicate = (row, clause) => {
31
- const column = columnOf(row, clause.key, clause.field);
45
+ const own = columnOf(row, clause.key, clause.field);
46
+ const column = clause.textual ? textOf(own) : own;
32
47
  const { value } = clause;
33
48
  const missing = value === void 0 || value === null;
34
49
  const insensitive = clause.mode === "insensitive" && typeof value === "string";
35
50
  const pattern = (text) => insensitive ? column.ilike(text) : column.like(text);
36
- switch (clause.operator) {
51
+ switch (clause.operator ?? "eq") {
37
52
  case "ne":
38
53
  if (value === null) return column.isNot(null);
39
54
  return value === void 0 ? none(column) : insensitive ? not(column.ilike(escapeLike(value))) : column.isNot(value);
@@ -53,9 +68,10 @@ const predicate = (row, clause) => {
53
68
  case "contains": return missing ? none(column) : pattern(`%${escapeLike(value)}%`);
54
69
  case "starts_with": return missing ? none(column) : pattern(`${escapeLike(value)}%`);
55
70
  case "ends_with": return missing ? none(column) : pattern(`%${escapeLike(value)}`);
56
- default:
71
+ case "eq":
57
72
  if (value === null) return column.is(null);
58
73
  return value === void 0 ? none(column) : insensitive ? column.ilike(escapeLike(value)) : column.is(value);
74
+ default: throw new Error(`symmetria: better-auth's where on "${clause.model}" uses the operator "${String(clause.operator)}", which this adapter does not know; it knows eq, ne, lt, lte, gt, gte, in, not_in, contains, starts_with and ends_with`);
59
75
  }
60
76
  };
61
77
  /** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */
@@ -148,6 +164,12 @@ const identifierOf = (name) => {
148
164
  const named = /^[\p{ID_Start}$_]/u.test(joined) ? joined : `_${joined}`;
149
165
  return TAKEN.has(named) ? `${named}Table` : named;
150
166
  };
167
+ /**
168
+ * A key as an object literal declares it: as it is when it is a JavaScript
169
+ * name, quoted otherwise (`"first-name"`); better-auth takes any text as the
170
+ * key of a field.
171
+ */
172
+ const propertyOf = (key) => /^[\p{ID_Start}$_][\p{ID_Continue}$]*$/u.test(key) ? key : JSON.stringify(key);
151
173
  /** The relation a reference field becomes: `userId` → `user`, `requestedBy` stays. */
152
174
  const relationOf = (key) => key.length > 2 && key.endsWith("Id") ? key.slice(0, -2) : key;
153
175
  /**
@@ -217,11 +239,11 @@ const authSchemaSource = (input, options = {}) => {
217
239
  if (shared || self || action === "noAction") {
218
240
  if (self) builders.add("self");
219
241
  const inverse = shared || self ? `.inverse(${JSON.stringify(`${name}By${relation[0].toUpperCase()}${relation.slice(1)}`)})` : "";
220
- return ` ${relation}: ${self ? "self" : identifier(target)}${by}${keyColumn}${nullable ? ".nullable" : ""}${unique ? ".unique" : ".index"}${action ? `.onDelete.${action}` : ""}${inverse},`;
242
+ return ` ${propertyOf(relation)}: ${self ? "self" : identifier(target)}${by}${keyColumn}${nullable ? ".nullable" : ""}${unique ? ".unique" : ".index"}${action ? `.onDelete.${action}` : ""}${inverse},`;
221
243
  }
222
244
  const claim = nullable ? "maybe" : "one";
223
245
  builders.add(claim);
224
- return ` ${relation}: ${claim}(${identifier(target)})${action ? `.${action}` : ""}${unique ? ".unique" : ""}${by}${keyColumn},`;
246
+ return ` ${propertyOf(relation)}: ${claim}(${identifier(target)})${action ? `.${action}` : ""}${unique ? ".unique" : ""}${by}${keyColumn},`;
225
247
  }
226
248
  let type;
227
249
  if (Array.isArray(field.type)) {
@@ -233,14 +255,17 @@ const authSchemaSource = (input, options = {}) => {
233
255
  const fallback = field.defaultValue;
234
256
  const literal = typeof fallback === "string" || typeof fallback === "number" || typeof fallback === "boolean" ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})` : "";
235
257
  const indexed = (field.index === true || single.has(key)) && !unique;
236
- return ` ${key}: ${type}${sqlName ? `.named(${JSON.stringify(sqlName)})` : ""}${field.required === false ? ".nullable" : ""}${unique ? ".unique" : ""}${indexed ? ".index" : ""}${literal},`;
258
+ return ` ${propertyOf(key)}: ${type}${sqlName ? `.named(${JSON.stringify(sqlName)})` : ""}${field.required === false ? ".nullable" : ""}${unique ? ".unique" : ""}${indexed ? ".index" : ""}${literal},`;
237
259
  });
238
260
  if (composite.length) builders.add("index");
239
261
  return [
240
262
  `export const ${name} = table({`,
241
263
  " id: text,",
242
264
  ...lines,
243
- composite.length ? `}).indexes((${name}) => ({\n${composite.map((definition) => ` ${definition.fields.join("_").replace(/_(\w)/g, (_match, letter) => letter.toUpperCase())}: index(${definition.fields.map((field) => `${name}.${columnKey(field)}`).join(", ")})${definition.unique ? ".unique" : ""},`).join("\n")}\n}));` : "});"
265
+ composite.length ? `}).indexes((${name}) => ({\n${composite.map((definition) => ` ${propertyOf(definition.fields.join("_").replace(/_(\w)/g, (_match, letter) => letter.toUpperCase()))}: index(${definition.fields.map((field) => {
266
+ const key = columnKey(field);
267
+ return propertyOf(key) === key ? `${name}.${key}` : `${name}[${JSON.stringify(key)}]`;
268
+ }).join(", ")})${definition.unique ? ".unique" : ""},`).join("\n")}\n}));` : "});"
244
269
  ].join("\n");
245
270
  });
246
271
  return [
@@ -268,7 +293,7 @@ const symmetriaAdapter = (db, options = {}) => {
268
293
  let authOptions;
269
294
  let columns;
270
295
  const columnsOf = (model) => {
271
- columns ??= new Map((db.$snapshot?.()?.tables ?? []).map((table) => [table.name, new Set(table.columns.map((column) => column.name))]));
296
+ columns ??= new Map((db.$snapshot?.()?.tables ?? []).map((table) => [table.name, new Map(table.columns.map((column) => [column.name, column.enumerationValues]))]));
272
297
  return columns.get(model);
273
298
  };
274
299
  const build = (connection) => createAdapterFactory({
@@ -290,20 +315,32 @@ const symmetriaAdapter = (db, options = {}) => {
290
315
  if (!handle) throw new Error(`symmetria: better-auth uses a table "${model}" that the schema does not have; run \`npx auth generate\` and add it`);
291
316
  return handle;
292
317
  };
318
+ const fieldsOf = (model) => {
319
+ try {
320
+ return schema[getDefaultModelName(model)]?.fields ?? {};
321
+ } catch {
322
+ return {};
323
+ }
324
+ };
293
325
  const relationKeys = /* @__PURE__ */ new Map();
294
326
  const relationKeysOf = (model) => {
295
327
  let keys = relationKeys.get(model);
296
328
  if (!keys) {
297
329
  const present = columnsOf(model);
298
- let fields = {};
299
- try {
300
- fields = schema[getDefaultModelName(model)]?.fields ?? {};
301
- } catch {}
302
- keys = new Map(Object.entries(fields).flatMap(([key, field]) => field.references && present && !present.has(key) && present.has(`${key}Id`) ? [[key, `${key}Id`]] : []));
330
+ keys = new Map(Object.entries(fieldsOf(model)).flatMap(([key, field]) => field.references && present && !present.has(key) && present.has(`${key}Id`) ? [[key, `${key}Id`]] : []));
303
331
  relationKeys.set(model, keys);
304
332
  }
305
333
  return keys;
306
334
  };
335
+ const storedNames = /* @__PURE__ */ new Map();
336
+ const fieldOfStored = (model, name) => {
337
+ let names = storedNames.get(model);
338
+ if (!names) {
339
+ names = new Map(Object.entries(fieldsOf(model)).map(([key, field]) => [field.fieldName || key, key]));
340
+ storedNames.set(model, names);
341
+ }
342
+ return names.get(name) ?? name;
343
+ };
307
344
  const keyOf = (model, field) => {
308
345
  let key;
309
346
  try {
@@ -326,16 +363,10 @@ const symmetriaAdapter = (db, options = {}) => {
326
363
  return;
327
364
  }
328
365
  };
329
- const keyed = (model, data) => Object.fromEntries(Object.entries(data).map(([field, value]) => [keyOf(model, field), value]));
330
- const isField = (model, key) => {
331
- if (key === "id") return true;
332
- try {
333
- const fields = schema[getDefaultModelName(model)]?.fields;
334
- return fields !== void 0 && Object.hasOwn(fields, key);
335
- } catch {
336
- return false;
337
- }
338
- };
366
+ const keyed = (model, data) => Object.fromEntries(Object.entries(data).map(([name, value]) => {
367
+ return [keyOf(model, fieldOfStored(model, name)), value];
368
+ }));
369
+ const isField = (model, key) => key === "id" || Object.hasOwn(fieldsOf(model), key);
339
370
  const fieldOf = (model, key) => {
340
371
  if (isField(model, key)) return key;
341
372
  const field = key.slice(0, -2);
@@ -356,16 +387,36 @@ const symmetriaAdapter = (db, options = {}) => {
356
387
  }
357
388
  return Object.fromEntries([...own, ...fields]);
358
389
  };
359
- const where = (model, clauses) => (clauses ?? []).map((clause) => ({
360
- ...clause,
361
- key: keyOf(model, clause.field),
362
- value: comparable(typeOf(model, clause.field), clause.value)
363
- }));
390
+ const where = (model, clauses) => (clauses ?? []).map((clause) => {
391
+ const field = fieldOfStored(model, clause.field);
392
+ const key = keyOf(model, field);
393
+ const value = comparable(typeOf(model, field), clause.value);
394
+ const labels = columnsOf(model)?.get(key);
395
+ return {
396
+ ...clause,
397
+ model,
398
+ key,
399
+ value,
400
+ textual: labels !== void 0 && !(EQUALITY.has(clause.operator ?? "eq") && [value].flat().every((item) => item === null || item === void 0 || labels.includes(item)))
401
+ };
402
+ });
403
+ const ordering = (model, sortBy) => {
404
+ const key = keyOf(model, sortBy.field);
405
+ return columnsOf(model)?.get(key) ? (row) => textOf(columnOf(row, key, sortBy.field))[sortBy.direction === "desc" ? "descending" : "ascending"] : { [key]: sortBy.direction };
406
+ };
364
407
  const read = (model, select, query) => select?.length ? table(model)((row) => Object.fromEntries(select.map((field) => {
365
408
  const key = keyOf(model, field);
366
409
  return [key, columnOf(row, key, field)];
367
410
  })), query) : table(model)(query);
368
411
  const filtered = (model, mutation, clauses) => clauses?.length ? mutation.where(filter(where(model, clauses))) : mutation.all();
412
+ const single = (handle, model, clauses) => {
413
+ const keyedWhere = where(model, clauses);
414
+ const condition = keyedWhere.length ? filter(keyedWhere) : void 0;
415
+ return (target) => [...condition ? [condition(target)] : [], columnOf(target, "id", "id").in(handle((first) => ({ id: first.id }), {
416
+ where: condition,
417
+ limit: 1
418
+ }))];
419
+ };
369
420
  const refusing = async (method, model, run) => {
370
421
  try {
371
422
  return await run();
@@ -384,7 +435,7 @@ const symmetriaAdapter = (db, options = {}) => {
384
435
  where: filter(where(model, clauses)),
385
436
  limit,
386
437
  offset,
387
- orderBy: sortBy ? { [keyOf(model, sortBy.field)]: sortBy.direction } : void 0
438
+ orderBy: sortBy ? ordering(model, sortBy) : void 0
388
439
  })).map((row) => fielded(model, row)),
389
440
  count: ({ model, where: clauses }) => table(model)({ where: filter(where(model, clauses)) }).count(),
390
441
  update: async ({ model, where: clauses, update }) => {
@@ -397,28 +448,19 @@ const symmetriaAdapter = (db, options = {}) => {
397
448
  },
398
449
  deleteMany: async ({ model, where: clauses }) => (await refusing("deleteMany", model, () => filtered(model, table(model).delete(), clauses))).affectedRows,
399
450
  consumeOne: async ({ model, where: clauses }) => {
400
- const found = await table(model)({
401
- where: filter(where(model, clauses)),
402
- limit: 1
403
- }).first();
404
- if (!found) return null;
405
- const [row] = await table(model).byId(found.id).delete().returning();
451
+ const handle = table(model);
452
+ const [row] = await handle.delete().where(single(handle, model, clauses)).returning();
406
453
  return fielded(model, row ?? null);
407
454
  },
408
455
  incrementOne: async ({ model, where: clauses, increment, set }) => {
409
456
  const handle = table(model);
410
- const keyedWhere = where(model, clauses);
411
- const condition = keyedWhere.length ? filter(keyedWhere) : void 0;
412
457
  const [row] = await handle.update((current) => ({
413
458
  ...keyed(model, set ?? {}),
414
- ...Object.fromEntries(Object.entries(increment).map(([field, delta]) => {
415
- const key = keyOf(model, field);
416
- return [key, coalesce(columnOf(current, key, field), 0).plus(delta)];
459
+ ...Object.fromEntries(Object.entries(increment).map(([name, delta]) => {
460
+ const key = keyOf(model, fieldOfStored(model, name));
461
+ return [key, coalesce(columnOf(current, key, name), 0).plus(delta)];
417
462
  }))
418
- })).where((target) => [...condition ? [condition(target)] : [], columnOf(target, "id", "id").in(handle((first) => ({ id: first.id }), {
419
- where: condition,
420
- limit: 1
421
- }))]).returning();
463
+ })).where(single(handle, model, clauses)).returning();
422
464
  return fielded(model, row ?? null);
423
465
  },
424
466
  createSchema: async ({ tables, file }) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"better-auth.js","names":[],"sources":["../src/entries/better-auth.ts"],"sourcesContent":["/**\n * `symmetria/better-auth`: a better-auth database adapter over a Symmetria\n * database: `betterAuth({ database: symmetriaAdapter(db) })`. The auth tables\n * are tables of your schema, keyed and named the way better-auth names its\n * models and fields (`user.emailVerified`), so they are migrated, related and\n * queried like the rest; `npx auth generate` writes them.\n */\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n createAdapterFactory,\n type CleanedWhere,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { and, coalesce, not, or } from \"../query/expressions\";\n\nexport type SymmetriaAdapterOptions = {\n /** Tables are keyed in the plural (`users`, `sessions`). */\n readonly usePlural?: boolean;\n readonly debugLogs?: DBAdapterDebugLogOption;\n};\n\n// better-auth names tables and fields at run time, so the adapter reaches\n// them by key and leaves the typed API to the application.\ntype Loose = any;\ntype Tables = Record<\n string,\n {\n modelName: string;\n fields: Record<string, Field>;\n indexes?: readonly {\n fields: readonly string[];\n unique?: boolean | undefined;\n }[];\n }\n>;\ntype Field = {\n type: string | readonly string[];\n required?: boolean | undefined;\n unique?: boolean | undefined;\n index?: boolean | undefined;\n bigint?: boolean | undefined;\n fieldName?: string | undefined;\n defaultValue?: unknown;\n references?:\n | { model: string; field: string; onDelete?: string | undefined }\n | undefined;\n};\n\nconst escapeLike = (value: unknown): string =>\n String(value).replace(/[\\\\%_]/g, (character) => `\\\\${character}`);\n\n/** A where clause whose field is already the table's key. */\ntype KeyedWhere = CleanedWhere & { readonly key: string };\n\n/** `target[key]`, unless it is only what every object inherits (`constructor`). */\nconst member = (target: Loose, key: string): Loose => {\n const value = target[key];\n\n return value === (Object.prototype as Loose)[key] ? undefined : value;\n};\n\n/** The column `key` of a row, for better-auth's field `field`. */\nconst columnOf = (row: Loose, key: string, field: string): Loose => {\n const column = member(row, key);\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${field}\", which the table does not have`,\n );\n }\n\n return column;\n};\n\n/**\n * A where value in the form its field's column compares. better-auth passes\n * request values on as they come (the admin plugin's `filterValue: 1984` for\n * a text field): node-postgres sends a number untyped, which PostgreSQL reads\n * as text, while Bun.SQL binds it as an integer and the comparison fails, so a\n * string field gets a string on every driver. A list for a boolean field\n * reads \"true\" and \"false\" as better-auth reads a single value.\n */\nconst comparable = (\n type: Field[\"type\"] | undefined,\n value: unknown,\n): unknown => {\n if (Array.isArray(value)) {\n return value.map((item) => comparable(type, item));\n }\n\n if (\n (type === \"string\" || Array.isArray(type)) &&\n (typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\")\n ) {\n return String(value);\n }\n\n return type === \"boolean\" && (value === \"true\" || value === \"false\")\n ? value === \"true\"\n : value;\n};\n\n// A comparison without a value matches no row, as `= NULL` does in\n// better-auth's SQL adapters: a request that names a filter field and no\n// value (`listMembers?filterField=role`) passes `undefined`.\nconst none = (column: Loose) => column.in([]);\n\nconst predicate = (row: Loose, clause: KeyedWhere) => {\n const column = columnOf(row, clause.key, clause.field);\n const { value } = clause;\n const missing = value === undefined || value === null;\n const insensitive =\n clause.mode === \"insensitive\" && typeof value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n if (value === null) {\n return column.isNot(null);\n }\n\n return value === undefined\n ? none(column)\n : insensitive\n ? not(column.ilike(escapeLike(value)))\n : column.isNot(value);\n case \"in\":\n case \"not_in\": {\n const list: unknown[] = Array.isArray(value) ? value : [value];\n const present = list.filter(\n (item) => item !== undefined && item !== null,\n );\n // A list compared without case: one ILIKE per value, as a single value is.\n const insensitiveList =\n clause.mode === \"insensitive\" &&\n present.length > 0 &&\n present.every((item) => typeof item === \"string\");\n\n if (clause.operator === \"in\") {\n // NULL is in no list, as in SQL.\n return insensitiveList\n ? or(...present.map((item) => column.ilike(escapeLike(item))))\n : column.in(present);\n }\n\n // `NOT IN (…, NULL)` holds for no row, as in SQL.\n if (present.length < list.length) {\n return none(column);\n }\n\n return insensitiveList\n ? and(...present.map((item) => not(column.ilike(escapeLike(item)))))\n : column.notIn(present);\n }\n case \"gt\":\n return missing ? none(column) : column.above(value);\n case \"gte\":\n return missing ? none(column) : column.atLeast(value);\n case \"lt\":\n return missing ? none(column) : column.below(value);\n case \"lte\":\n return missing ? none(column) : column.atMost(value);\n case \"contains\":\n return missing ? none(column) : pattern(`%${escapeLike(value)}%`);\n case \"starts_with\":\n return missing ? none(column) : pattern(`${escapeLike(value)}%`);\n case \"ends_with\":\n return missing ? none(column) : pattern(`%${escapeLike(value)}`);\n default:\n if (value === null) {\n return column.is(null);\n }\n\n return value === undefined\n ? none(column)\n : insensitive\n ? column.ilike(escapeLike(value))\n : column.is(value);\n }\n};\n\n/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */\nconst filter = (where: readonly KeyedWhere[] | undefined) => (row: Loose) => {\n const clauses = where ?? [];\n const all = clauses\n .filter((clause) => clause.connector !== \"OR\")\n .map((clause) => predicate(row, clause));\n const any = clauses\n .filter((clause) => clause.connector === \"OR\")\n .map((clause) => predicate(row, clause));\n\n return and(...all, any.length > 0 ? or(...any) : undefined);\n};\n\nconst COLUMN_TYPES: Readonly<Record<string, string>> = {\n string: \"text\",\n boolean: \"bool\",\n date: \"timestamptz\",\n json: \"jsonb()\",\n \"string[]\": \"text.array\",\n \"number[]\": \"int.array\",\n};\n\n/** A key's SQL name under schema()'s default casing (`requestedBy` → `requested_by`). */\nconst snakeCase = (name: string): string =>\n name.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase();\n\n/** Names a module cannot declare: JavaScript's reserved words and what it imports. */\nconst TAKEN: ReadonlySet<string> = new Set([\n \"arguments\",\n \"await\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"interface\",\n \"let\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"static\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n \"Infinity\",\n \"NaN\",\n \"authTables\",\n \"bigint\",\n \"bool\",\n \"index\",\n \"int\",\n \"jsonb\",\n \"maybe\",\n \"one\",\n \"oneOf\",\n \"self\",\n \"table\",\n \"text\",\n \"timestamptz\",\n]);\n\n/** A JavaScript name for a model: `auth-user` → `authUser`, `default` → `defaultTable`. */\nconst identifierOf = (name: string): string => {\n const joined = name\n .split(/[^\\p{ID_Continue}$]+/u)\n .filter(Boolean)\n .map((word, position) =>\n position ? `${word[0]!.toUpperCase()}${word.slice(1)}` : word,\n )\n .join(\"\");\n const named = /^[\\p{ID_Start}$_]/u.test(joined) ? joined : `_${joined}`;\n\n return TAKEN.has(named) ? `${named}Table` : named;\n};\n\n/** The relation a reference field becomes: `userId` → `user`, `requestedBy` stays. */\nconst relationOf = (key: string): string =>\n key.length > 2 && key.endsWith(\"Id\") ? key.slice(0, -2) : key;\n\n/**\n * The auth tables as a Symmetria schema module, for `npx auth generate`.\n * Tables come out in an order where each one follows the tables it\n * references; spread `authTables` into `schema({ ... })`. With `usePlural`\n * the tables are keyed in the plural (`users`), as the adapter then asks for\n * them; `casing` is the schema's (`\"preserve\"` keeps a reference key such as\n * `requestedBy` as its SQL name).\n */\nexport const authSchemaSource = (\n input: Tables,\n options: {\n readonly usePlural?: boolean;\n readonly casing?: \"snake_case\" | \"preserve\";\n } = {},\n): string => {\n const tables: Tables = options.usePlural\n ? Object.fromEntries(\n Object.entries(input).map(([model, entry]) => [\n model,\n { ...entry, modelName: `${entry.modelName}s` },\n ]),\n )\n : input;\n const builders = new Set<string>([\"table\", \"text\"]);\n const models = Object.values(tables);\n const nameOf = (model: string): string =>\n tables[model]?.modelName ??\n models.find((entry) => entry.modelName === model)?.modelName ??\n model;\n // Each table's export name: its model name where that is a free JavaScript\n // name, otherwise one made from it (`\"auth-user\": authUser`).\n const identifiers = new Map<string, string>();\n const used = new Set<string>();\n\n for (const plain of [true, false]) {\n for (const { modelName } of models) {\n const base = identifierOf(modelName);\n\n if ((base === modelName) !== plain || identifiers.has(modelName)) {\n continue;\n }\n\n let name = base;\n\n for (let count = 2; used.has(name); count++) {\n name = `${base}${count}`;\n }\n\n used.add(name);\n identifiers.set(modelName, name);\n }\n }\n\n const identifier = (modelName: string): string =>\n identifiers.get(modelName) ?? modelName;\n const ordered: typeof models = [];\n const pending = [...models];\n\n // References first; a cycle keeps the order better-auth gave.\n while (pending.length) {\n const next =\n pending.find((entry) =>\n Object.values(entry.fields).every(\n (field) =>\n !field.references ||\n nameOf(field.references.model) === entry.modelName ||\n ordered.some(\n (done) => done.modelName === nameOf(field.references!.model),\n ),\n ),\n ) ?? pending[0]!;\n\n ordered.push(next);\n pending.splice(pending.indexOf(next), 1);\n }\n\n const declarations = ordered.map((entry) => {\n const name = identifier(entry.modelName);\n const fields = entry.fields;\n // A reference is a relation, whose key column is `<relation>Id`.\n const columnKey = (key: string): string =>\n fields[key]?.references ? `${relationOf(key)}Id` : key;\n // A single-field index the table declares (device-authorization's\n // unique `userCode`) is the column's own `.unique` or `.index`.\n const single = new Map<string, boolean>();\n const composite: NonNullable<Tables[string][\"indexes\"]>[number][] = [];\n\n for (const definition of entry.indexes ?? []) {\n const [only, ...others] = definition.fields;\n\n if (only !== undefined && !others.length && Object.hasOwn(fields, only)) {\n single.set(\n only,\n single.get(only) === true || definition.unique === true,\n );\n } else {\n composite.push(definition);\n }\n }\n\n const targets = Object.values(fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(fields).map(([key, field]) => {\n // The SQL name better-auth was given, whenever it is not the key: it\n // is the column's name under either casing.\n const sqlName =\n field.fieldName && field.fieldName !== key\n ? field.fieldName\n : undefined;\n const unique = field.unique === true || single.get(key) === true;\n const reference = field.references;\n\n if (reference) {\n const target = nameOf(reference.model);\n const relation = relationOf(key);\n\n const clash = [relation, `${relation}Id`].find(\n (other) => other !== key && Object.hasOwn(fields, other),\n );\n\n if (clash) {\n throw new Error(\n `symmetria: ${entry.modelName}.${key} references ${target} and becomes the relation \"${relation}\" with the key \"${relation}Id\", but ${entry.modelName} has another field \"${clash}\"; rename one of the two`,\n );\n }\n\n // A key that does not end in `Id` keeps its own SQL name; the\n // relation would otherwise call it `<relation>_id`.\n const column =\n sqlName ??\n (relation === key\n ? options.casing === \"preserve\"\n ? key\n : snakeCase(key)\n : undefined);\n const keyColumn =\n column === undefined ? \"\" : `.column(${JSON.stringify(column)})`;\n // A reference to a field other than the id names it.\n const targetFields = models.find(\n (model) => model.modelName === target,\n )?.fields;\n const targetKey =\n reference.field === \"id\" ||\n !targetFields ||\n Object.hasOwn(targetFields, reference.field)\n ? reference.field\n : (Object.entries(targetFields).find(\n ([, candidate]) => candidate.fieldName === reference.field,\n )?.[0] ?? reference.field);\n const by =\n targetKey === \"id\"\n ? \"\"\n : `.by(${JSON.stringify(targetFields?.[targetKey]?.references ? `${relationOf(targetKey)}Id` : targetKey)})`;\n // better-auth's own migrations cascade when a reference names no\n // action. They give a key no default, so its SET DEFAULT sets NULL:\n // SET NULL for an optional key, a refused delete for a required one.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\" ||\n (reference.onDelete === \"set default\" &&\n field.required === false)\n ? \"setNull\"\n : reference.onDelete === \"no action\" ||\n reference.onDelete === \"set default\"\n ? \"noAction\"\n : undefined;\n const nullable = field.required === false || action === \"setNull\";\n const self = target === entry.modelName;\n const shared = targets.filter((other) => other === target).length > 1;\n\n // Two keys to one table need names for their reverse sides; NO\n // ACTION is spelled on the reference itself.\n if (shared || self || action === \"noAction\") {\n if (self) {\n builders.add(\"self\");\n }\n\n const inverse =\n shared || self\n ? `.inverse(${JSON.stringify(`${name}By${relation[0]!.toUpperCase()}${relation.slice(1)}`)})`\n : \"\";\n\n return ` ${relation}: ${self ? \"self\" : identifier(target)}${by}${keyColumn}${nullable ? \".nullable\" : \"\"}${unique ? \".unique\" : \".index\"}${action ? `.onDelete.${action}` : \"\"}${inverse},`;\n }\n\n const claim = nullable ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${identifier(target)})${action ? `.${action}` : \"\"}${unique ? \".unique\" : \"\"}${by}${keyColumn},`;\n }\n\n let type: string;\n\n if (Array.isArray(field.type)) {\n builders.add(\"oneOf\");\n type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(\", \")})`;\n } else if (field.type === \"number\") {\n type = field.bigint ? \"bigint\" : \"int\";\n } else {\n type = COLUMN_TYPES[field.type as string] ?? \"text\";\n }\n\n builders.add(type.split(/[.(]/)[0]!);\n\n const fallback = field.defaultValue;\n const literal =\n typeof fallback === \"string\" ||\n typeof fallback === \"number\" ||\n typeof fallback === \"boolean\"\n ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})`\n : \"\";\n const indexed = (field.index === true || single.has(key)) && !unique;\n\n return ` ${key}: ${type}${sqlName ? `.named(${JSON.stringify(sqlName)})` : \"\"}${field.required === false ? \".nullable\" : \"\"}${unique ? \".unique\" : \"\"}${indexed ? \".index\" : \"\"}${literal},`;\n });\n\n if (composite.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${name} = table({`,\n \" id: text,\",\n ...lines,\n composite.length\n ? `}).indexes((${name}) => ({\\n${composite\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((field) => `${name}.${columnKey(field)}`).join(\", \")})${definition.unique ? \".unique\" : \"\"},`,\n )\n .join(\"\\n\")}\\n}));`\n : \"});\",\n ].join(\"\\n\");\n });\n\n return [\n \"// Written by `auth generate` through symmetria/better-auth.\",\n \"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).\",\n `import { ${[...builders].sort().join(\", \")} } from \"symmetria\";`,\n \"\",\n declarations.join(\"\\n\\n\"),\n \"\",\n `export const authTables = { ${ordered\n .map((entry) => {\n const name = identifier(entry.modelName);\n\n return name === entry.modelName\n ? name\n : `${JSON.stringify(entry.modelName)}: ${name}`;\n })\n .join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\n\nconst SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);\nconst SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a\n * `$scope()` of it) whose schema holds the auth tables; better-auth's own\n * transactions run inside `db.$transaction`.\n */\nexport const symmetriaAdapter = (\n db: object,\n options: SymmetriaAdapterOptions = {},\n) => {\n // What better-auth hands the adapter, kept for the adapters built around a transaction.\n let authOptions: BetterAuthOptions | undefined;\n // Each table's column keys, read once: they tell a reference written as a\n // relation (`requestedById`) from one written as a plain column\n // (`requestedBy`), as modules that earlier versions of `auth generate`\n // wrote declare it, so those modules keep working.\n let columns: ReadonlyMap<string, ReadonlySet<string>> | undefined;\n const columnsOf = (model: string): ReadonlySet<string> | undefined => {\n columns ??= new Map(\n ((db as Loose).$snapshot?.()?.tables ?? []).map((table: Loose) => [\n table.name,\n new Set(table.columns.map((column: Loose) => column.name)),\n ]),\n );\n\n return columns.get(model);\n };\n\n const build = (connection: Loose): ReturnType<typeof createAdapterFactory> =>\n createAdapterFactory({\n config: {\n adapterId: \"symmetria\",\n adapterName: \"Symmetria\",\n usePlural: options.usePlural ?? false,\n debugLogs: options.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsJSON: true,\n supportsArrays: true,\n // Ids are text columns better-auth fills; `generateId: \"serial\"` is\n // refused when better-auth starts rather than at the first insert.\n supportsNumericIds: false,\n transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: ({\n getDefaultFieldName,\n getDefaultModelName,\n getFieldAttributes,\n getFieldName,\n schema,\n }) => {\n const table = (model: string) => {\n const handle = member(connection, model);\n\n if (!handle) {\n throw new Error(\n `symmetria: better-auth uses a table \"${model}\" that the schema does not have; run \\`npx auth generate\\` and add it`,\n );\n }\n\n return handle;\n };\n // A reference field the table holds as a relation's key column\n // `<field>Id`: `requestedBy` is the relation `requestedBy` and the\n // column `requestedById`. (`userId` is the relation `user` and keeps\n // its key.)\n const relationKeys = new Map<string, ReadonlyMap<string, string>>();\n const relationKeysOf = (model: string): ReadonlyMap<string, string> => {\n let keys = relationKeys.get(model);\n\n if (!keys) {\n const present = columnsOf(model);\n let fields: Record<string, Loose> = {};\n\n try {\n fields = schema[getDefaultModelName(model)]?.fields ?? {};\n } catch {\n // Not one of better-auth's models.\n }\n\n keys = new Map(\n Object.entries(fields).flatMap(([key, field]) =>\n field.references &&\n present &&\n !present.has(key) &&\n present.has(`${key}Id`)\n ? [[key, `${key}Id`] as const]\n : [],\n ),\n );\n relationKeys.set(model, keys);\n }\n\n return keys;\n };\n // better-auth hands over rows and clauses by each field's database\n // name (`fields: { emailVerified: \"email_verified\" }`); the tables are\n // keyed by its field names (`emailVerified`) with that SQL name.\n const keyOf = (model: string, field: string): string => {\n let key: string;\n\n try {\n key = getDefaultFieldName({ model, field });\n } catch {\n return field;\n }\n\n return relationKeysOf(model).get(key) ?? key;\n };\n const typeOf = (\n model: string,\n field: string,\n ): Field[\"type\"] | undefined => {\n try {\n return getFieldAttributes({ model, field }).type;\n } catch {\n return undefined;\n }\n };\n const keyed = (model: string, data: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(data).map(([field, value]) => [\n keyOf(model, field),\n value,\n ]),\n );\n // A key of the table that is one of better-auth's fields (`name`, `userId`).\n const isField = (model: string, key: string): boolean => {\n if (key === \"id\") {\n return true;\n }\n\n try {\n const fields = schema[getDefaultModelName(model)]?.fields;\n\n return fields !== undefined && Object.hasOwn(fields, key);\n } catch {\n return false;\n }\n };\n // The better-auth field a key of the table holds, if any.\n const fieldOf = (model: string, key: string): string | undefined => {\n if (isField(model, key)) {\n return key;\n }\n\n const field = key.slice(0, -2);\n\n return key.endsWith(\"Id\") && relationKeysOf(model).get(field) === key\n ? field\n : undefined;\n };\n // A `bigint` column (`rateLimit.lastRequest`) reads as a bigint;\n // better-auth types its number fields as numbers, so a safe integer\n // goes back as one.\n const output = (model: string, field: string, value: unknown) =>\n typeof value === \"bigint\" &&\n value >= SAFE_MIN &&\n value <= SAFE_MAX &&\n typeOf(model, field) === \"number\"\n ? Number(value)\n : value;\n // Rows go back under better-auth's database names. A column of the\n // application's own (`plan`) is not a better-auth field: it keeps its\n // key, and a field's value wins over it when the two names meet\n // (`fields: { name: \"nickname\" }` next to an app column `nickname`).\n const fielded = (\n model: string,\n row: Record<string, unknown> | null,\n ) => {\n if (!row) {\n return null;\n }\n\n const own: [string, unknown][] = [];\n const fields: [string, unknown][] = [];\n\n for (const [key, value] of Object.entries(row)) {\n const field = fieldOf(model, key);\n\n if (field === undefined) {\n own.push([key, value]);\n } else {\n fields.push([\n getFieldName({ model, field }),\n output(model, field, value),\n ]);\n }\n }\n\n return Object.fromEntries([...own, ...fields]);\n };\n const where = (\n model: string,\n clauses: readonly CleanedWhere[] | undefined,\n ): KeyedWhere[] =>\n (clauses ?? []).map((clause) => ({\n ...clause,\n key: keyOf(model, clause.field),\n value: comparable(\n typeOf(model, clause.field),\n clause.value,\n ) as CleanedWhere[\"value\"],\n }));\n // A read of the whole row, or of the fields better-auth selects.\n const read = (\n model: string,\n select: readonly string[] | undefined,\n query: object,\n ) =>\n select?.length\n ? table(model)(\n (row: Loose) =>\n Object.fromEntries(\n select.map((field) => {\n const key = keyOf(model, field);\n\n return [key, columnOf(row, key, field)];\n }),\n ),\n query,\n )\n : table(model)(query);\n // An UPDATE or DELETE without a filter is refused unless spelled\n // out; better-auth means every row when it sends none.\n const filtered = (\n model: string,\n mutation: Loose,\n clauses: readonly CleanedWhere[] | undefined,\n ) =>\n clauses?.length\n ? mutation.where(filter(where(model, clauses)))\n : mutation.all();\n // A filter that holds for every row (`not_in` an empty list, `ne`\n // null on a required field) is refused like a missing where().\n const refusing = async (\n method: string,\n model: string,\n run: () => Loose,\n ): Promise<Loose> => {\n try {\n return await run();\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"leaves no condition\")\n ) {\n throw new Error(\n `symmetria: better-auth's ${method}() on \"${model}\" has a where that holds for every row (such as not_in an empty list, or ne null on a required field), so the adapter refuses it rather than write every row; call ${method}() without a where to write every row`,\n { cause: error },\n );\n }\n\n throw error;\n }\n };\n\n return {\n create: async ({ model, data }) =>\n fielded(\n model,\n await table(model).insert(keyed(model, data)).returning(),\n ) as never,\n\n findOne: async ({ model, where: clauses, select }) =>\n fielded(\n model,\n await read(model, select, {\n where: filter(where(model, clauses)),\n limit: 1,\n }).first(),\n ) as never,\n\n findMany: async ({\n model,\n where: clauses,\n limit,\n offset,\n sortBy,\n select,\n }) =>\n (\n await read(model, select, {\n where: filter(where(model, clauses)),\n limit,\n offset,\n orderBy: sortBy\n ? { [keyOf(model, sortBy.field)]: sortBy.direction }\n : undefined,\n })\n ).map((row: Record<string, unknown>) => fielded(model, row)),\n\n count: ({ model, where: clauses }) =>\n table(model)({ where: filter(where(model, clauses)) }).count(),\n\n update: async ({ model, where: clauses, update }) => {\n const [row] = await refusing(\"update\", model, () =>\n filtered(\n model,\n table(model).update(\n keyed(model, update as Record<string, unknown>),\n ),\n clauses,\n ).returning(),\n );\n\n return fielded(model, row ?? null) as never;\n },\n\n updateMany: async ({ model, where: clauses, update }) =>\n (\n await refusing(\"updateMany\", model, () =>\n filtered(\n model,\n table(model).update(keyed(model, update)),\n clauses,\n ),\n )\n ).affectedRows,\n\n delete: async ({ model, where: clauses }) => {\n await refusing(\"delete\", model, () =>\n filtered(model, table(model).delete(), clauses),\n );\n },\n\n deleteMany: async ({ model, where: clauses }) =>\n (\n await refusing(\"deleteMany\", model, () =>\n filtered(model, table(model).delete(), clauses),\n )\n ).affectedRows,\n\n // One row at most: the DELETE by key decides which of two\n // concurrent callers gets it.\n consumeOne: async ({ model, where: clauses }) => {\n const found = await table(model)({\n where: filter(where(model, clauses)),\n limit: 1,\n }).first();\n\n if (!found) {\n return null;\n }\n\n const [row] = await table(model)\n .byId(found.id)\n .delete()\n .returning();\n\n return fielded(model, row ?? null) as never;\n },\n\n // One row, as better-auth's SQL adapters change it: the first the\n // filter finds, written only while the filter still holds for it,\n // so a concurrent change that breaks the filter leaves it alone. A\n // NULL counter counts from 0, as better-auth's own fallback does.\n incrementOne: async ({ model, where: clauses, increment, set }) => {\n const handle = table(model);\n const keyedWhere = where(model, clauses);\n const condition = keyedWhere.length\n ? filter(keyedWhere)\n : undefined;\n const [row] = await handle\n .update((current: Loose) => ({\n ...keyed(model, set ?? {}),\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => {\n const key = keyOf(model, field);\n\n return [\n key,\n (coalesce as Loose)(\n columnOf(current, key, field),\n 0,\n ).plus(delta),\n ];\n }),\n ),\n }))\n .where((target: Loose) => [\n ...(condition ? [condition(target)] : []),\n columnOf(target, \"id\", \"id\").in(\n handle((first: Loose) => ({ id: first.id }), {\n where: condition,\n limit: 1,\n }),\n ),\n ])\n .returning();\n\n return fielded(model, row ?? null) as never;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables, {\n usePlural: options.usePlural ?? false,\n casing: (db as Loose).$snapshot?.()?.casing,\n }),\n path: file ?? \"./auth-schema.ts\",\n overwrite: true,\n }),\n };\n },\n });\n\n const adapter = build(db);\n\n return (betterAuthOptions: BetterAuthOptions) => {\n authOptions = betterAuthOptions;\n\n return adapter(betterAuthOptions);\n };\n};\n"],"mappings":";;;AAgDA,MAAM,cAAc,UAClB,OAAO,KAAK,CAAC,CAAC,QAAQ,YAAY,cAAc,KAAK,WAAW;;AAMlE,MAAM,UAAU,QAAe,QAAuB;CACpD,MAAM,QAAQ,OAAO;CAErB,OAAO,UAAW,OAAO,UAAoB,OAAO,KAAA,IAAY;AAClE;;AAGA,MAAM,YAAY,KAAY,KAAa,UAAyB;CAClE,MAAM,SAAS,OAAO,KAAK,GAAG;CAE9B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,MAAM,iCACnD;CAGF,OAAO;AACT;;;;;;;;;AAUA,MAAM,cACJ,MACA,UACY;CACZ,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,SAAS,WAAW,MAAM,IAAI,CAAC;CAGnD,KACG,SAAS,YAAY,MAAM,QAAQ,IAAI,OACvC,OAAO,UAAU,YAChB,OAAO,UAAU,YACjB,OAAO,UAAU,YAEnB,OAAO,OAAO,KAAK;CAGrB,OAAO,SAAS,cAAc,UAAU,UAAU,UAAU,WACxD,UAAU,SACV;AACN;AAKA,MAAM,QAAQ,WAAkB,OAAO,GAAG,CAAC,CAAC;AAE5C,MAAM,aAAa,KAAY,WAAuB;CACpD,MAAM,SAAS,SAAS,KAAK,OAAO,KAAK,OAAO,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CAAC;CAEH,MAAM,UAAU,MAAM,EAAE;CAExB,QAAQ,sBAAyC;EAC/C,cAAc;EAEd,OAAO,QAAQ,iBAAiB;CAClC;AACF"}
1
+ {"version":3,"file":"better-auth.js","names":[],"sources":["../src/entries/better-auth.ts"],"sourcesContent":["/**\n * `symmetria/better-auth`: a better-auth database adapter over a Symmetria\n * database: `betterAuth({ database: symmetriaAdapter(db) })`. The auth tables\n * are tables of your schema, keyed and named the way better-auth names its\n * models and fields (`user.emailVerified`), so they are migrated, related and\n * queried like the rest; `npx auth generate` writes them.\n */\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n createAdapterFactory,\n type CleanedWhere,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport {\n and,\n COLUMN_EXPRESSION,\n coalesce,\n createExpression,\n not,\n or,\n} from \"../query/expressions\";\nimport { asText } from \"../query/expressions/arithmetic\";\n\nexport type SymmetriaAdapterOptions = {\n /** Tables are keyed in the plural (`users`, `sessions`). */\n readonly usePlural?: boolean;\n readonly debugLogs?: DBAdapterDebugLogOption;\n};\n\n// better-auth names tables and fields at run time, so the adapter reaches\n// them by key and leaves the typed API to the application.\ntype Loose = any;\ntype Tables = Record<\n string,\n {\n modelName: string;\n fields: Record<string, Field>;\n indexes?: readonly {\n fields: readonly string[];\n unique?: boolean | undefined;\n }[];\n }\n>;\ntype Field = {\n type: string | readonly string[];\n required?: boolean | undefined;\n unique?: boolean | undefined;\n index?: boolean | undefined;\n bigint?: boolean | undefined;\n fieldName?: string | undefined;\n defaultValue?: unknown;\n references?:\n | { model: string; field: string; onDelete?: string | undefined }\n | undefined;\n};\n\nconst escapeLike = (value: unknown): string =>\n String(value).replace(/[\\\\%_]/g, (character) => `\\\\${character}`);\n\n/** A table's column keys, each with its labels when the column is an enum. */\ntype Labels = ReadonlyMap<string, readonly string[] | undefined>;\n\n/** The operators that test equality, whose answer is the same on an enum and on its text. */\nconst EQUALITY: ReadonlySet<string> = new Set([\"eq\", \"ne\", \"in\", \"not_in\"]);\n\n/** A where clause whose field is already the table's key. */\ntype KeyedWhere = CleanedWhere & {\n readonly key: string;\n readonly model: string;\n /** The column is an enum that this clause compares as its text. */\n readonly textual: boolean;\n};\n\n/**\n * An enum column as its text. better-auth's own adapters keep a field declared\n * as a list of literals in a text column, so it sorts and compares by spelling,\n * not by the order the labels were declared in, and a value that is none of the\n * labels matches no row where the enum itself would refuse it as an input.\n */\nconst textOf = (column: Loose): Loose =>\n createExpression(asText(column[COLUMN_EXPRESSION]));\n\n/** `target[key]`, unless it is only what every object inherits (`constructor`). */\nconst member = (target: Loose, key: string): Loose => {\n const value = target[key];\n\n return value === (Object.prototype as Loose)[key] ? undefined : value;\n};\n\n/** The column `key` of a row, for better-auth's field `field`. */\nconst columnOf = (row: Loose, key: string, field: string): Loose => {\n const column = member(row, key);\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${field}\", which the table does not have`,\n );\n }\n\n return column;\n};\n\n/**\n * A where value in the form its field's column compares. better-auth passes\n * request values on as they come (the admin plugin's `filterValue: 1984` for\n * a text field): node-postgres sends a number untyped, which PostgreSQL reads\n * as text, while Bun.SQL binds it as an integer and the comparison fails, so a\n * string field gets a string on every driver. A list for a boolean field\n * reads \"true\" and \"false\" as better-auth reads a single value.\n */\nconst comparable = (\n type: Field[\"type\"] | undefined,\n value: unknown,\n): unknown => {\n if (Array.isArray(value)) {\n return value.map((item) => comparable(type, item));\n }\n\n if (\n (type === \"string\" || Array.isArray(type)) &&\n (typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\")\n ) {\n return String(value);\n }\n\n return type === \"boolean\" && (value === \"true\" || value === \"false\")\n ? value === \"true\"\n : value;\n};\n\n// A comparison without a value matches no row, as `= NULL` does in\n// better-auth's SQL adapters: a request that names a filter field and no\n// value (`listMembers?filterField=role`) passes `undefined`.\nconst none = (column: Loose) => column.in([]);\n\nconst predicate = (row: Loose, clause: KeyedWhere) => {\n const own = columnOf(row, clause.key, clause.field);\n const column = clause.textual ? textOf(own) : own;\n const { value } = clause;\n const missing = value === undefined || value === null;\n const insensitive =\n clause.mode === \"insensitive\" && typeof value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n // better-auth fills in `eq`; a clause handed over without one means it too.\n switch (clause.operator ?? \"eq\") {\n case \"ne\":\n if (value === null) {\n return column.isNot(null);\n }\n\n return value === undefined\n ? none(column)\n : insensitive\n ? not(column.ilike(escapeLike(value)))\n : column.isNot(value);\n case \"in\":\n case \"not_in\": {\n const list: unknown[] = Array.isArray(value) ? value : [value];\n const present = list.filter(\n (item) => item !== undefined && item !== null,\n );\n // A list compared without case: one ILIKE per value, as a single value is.\n const insensitiveList =\n clause.mode === \"insensitive\" &&\n present.length > 0 &&\n present.every((item) => typeof item === \"string\");\n\n if (clause.operator === \"in\") {\n // NULL is in no list, as in SQL.\n return insensitiveList\n ? or(...present.map((item) => column.ilike(escapeLike(item))))\n : column.in(present);\n }\n\n // `NOT IN (…, NULL)` holds for no row, as in SQL.\n if (present.length < list.length) {\n return none(column);\n }\n\n return insensitiveList\n ? and(...present.map((item) => not(column.ilike(escapeLike(item)))))\n : column.notIn(present);\n }\n case \"gt\":\n return missing ? none(column) : column.above(value);\n case \"gte\":\n return missing ? none(column) : column.atLeast(value);\n case \"lt\":\n return missing ? none(column) : column.below(value);\n case \"lte\":\n return missing ? none(column) : column.atMost(value);\n case \"contains\":\n return missing ? none(column) : pattern(`%${escapeLike(value)}%`);\n case \"starts_with\":\n return missing ? none(column) : pattern(`${escapeLike(value)}%`);\n case \"ends_with\":\n return missing ? none(column) : pattern(`%${escapeLike(value)}`);\n case \"eq\":\n if (value === null) {\n return column.is(null);\n }\n\n return value === undefined\n ? none(column)\n : insensitive\n ? column.ilike(escapeLike(value))\n : column.is(value);\n default:\n // A later better-auth may add operators; read as equality, one would\n // match (and in a write, change) other rows than it names.\n throw new Error(\n `symmetria: better-auth's where on \"${clause.model}\" uses the operator \"${String(clause.operator)}\", which this adapter does not know; it knows eq, ne, lt, lte, gt, gte, in, not_in, contains, starts_with and ends_with`,\n );\n }\n};\n\n/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */\nconst filter = (where: readonly KeyedWhere[] | undefined) => (row: Loose) => {\n const clauses = where ?? [];\n const all = clauses\n .filter((clause) => clause.connector !== \"OR\")\n .map((clause) => predicate(row, clause));\n const any = clauses\n .filter((clause) => clause.connector === \"OR\")\n .map((clause) => predicate(row, clause));\n\n return and(...all, any.length > 0 ? or(...any) : undefined);\n};\n\nconst COLUMN_TYPES: Readonly<Record<string, string>> = {\n string: \"text\",\n boolean: \"bool\",\n date: \"timestamptz\",\n json: \"jsonb()\",\n \"string[]\": \"text.array\",\n \"number[]\": \"int.array\",\n};\n\n/** A key's SQL name under schema()'s default casing (`requestedBy` → `requested_by`). */\nconst snakeCase = (name: string): string =>\n name.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase();\n\n/** Names a module cannot declare: JavaScript's reserved words and what it imports. */\nconst TAKEN: ReadonlySet<string> = new Set([\n \"arguments\",\n \"await\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"interface\",\n \"let\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"static\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n \"Infinity\",\n \"NaN\",\n \"authTables\",\n \"bigint\",\n \"bool\",\n \"index\",\n \"int\",\n \"jsonb\",\n \"maybe\",\n \"one\",\n \"oneOf\",\n \"self\",\n \"table\",\n \"text\",\n \"timestamptz\",\n]);\n\n/** A JavaScript name for a model: `auth-user` → `authUser`, `default` → `defaultTable`. */\nconst identifierOf = (name: string): string => {\n const joined = name\n .split(/[^\\p{ID_Continue}$]+/u)\n .filter(Boolean)\n .map((word, position) =>\n position ? `${word[0]!.toUpperCase()}${word.slice(1)}` : word,\n )\n .join(\"\");\n const named = /^[\\p{ID_Start}$_]/u.test(joined) ? joined : `_${joined}`;\n\n return TAKEN.has(named) ? `${named}Table` : named;\n};\n\n/**\n * A key as an object literal declares it: as it is when it is a JavaScript\n * name, quoted otherwise (`\"first-name\"`); better-auth takes any text as the\n * key of a field.\n */\nconst propertyOf = (key: string): string =>\n /^[\\p{ID_Start}$_][\\p{ID_Continue}$]*$/u.test(key)\n ? key\n : JSON.stringify(key);\n\n/** The relation a reference field becomes: `userId` → `user`, `requestedBy` stays. */\nconst relationOf = (key: string): string =>\n key.length > 2 && key.endsWith(\"Id\") ? key.slice(0, -2) : key;\n\n/**\n * The auth tables as a Symmetria schema module, for `npx auth generate`.\n * Tables come out in an order where each one follows the tables it\n * references; spread `authTables` into `schema({ ... })`. With `usePlural`\n * the tables are keyed in the plural (`users`), as the adapter then asks for\n * them; `casing` is the schema's (`\"preserve\"` keeps a reference key such as\n * `requestedBy` as its SQL name).\n */\nexport const authSchemaSource = (\n input: Tables,\n options: {\n readonly usePlural?: boolean;\n readonly casing?: \"snake_case\" | \"preserve\";\n } = {},\n): string => {\n const tables: Tables = options.usePlural\n ? Object.fromEntries(\n Object.entries(input).map(([model, entry]) => [\n model,\n { ...entry, modelName: `${entry.modelName}s` },\n ]),\n )\n : input;\n const builders = new Set<string>([\"table\", \"text\"]);\n const models = Object.values(tables);\n const nameOf = (model: string): string =>\n tables[model]?.modelName ??\n models.find((entry) => entry.modelName === model)?.modelName ??\n model;\n // Each table's export name: its model name where that is a free JavaScript\n // name, otherwise one made from it (`\"auth-user\": authUser`).\n const identifiers = new Map<string, string>();\n const used = new Set<string>();\n\n for (const plain of [true, false]) {\n for (const { modelName } of models) {\n const base = identifierOf(modelName);\n\n if ((base === modelName) !== plain || identifiers.has(modelName)) {\n continue;\n }\n\n let name = base;\n\n for (let count = 2; used.has(name); count++) {\n name = `${base}${count}`;\n }\n\n used.add(name);\n identifiers.set(modelName, name);\n }\n }\n\n const identifier = (modelName: string): string =>\n identifiers.get(modelName) ?? modelName;\n const ordered: typeof models = [];\n const pending = [...models];\n\n // References first; a cycle keeps the order better-auth gave.\n while (pending.length) {\n const next =\n pending.find((entry) =>\n Object.values(entry.fields).every(\n (field) =>\n !field.references ||\n nameOf(field.references.model) === entry.modelName ||\n ordered.some(\n (done) => done.modelName === nameOf(field.references!.model),\n ),\n ),\n ) ?? pending[0]!;\n\n ordered.push(next);\n pending.splice(pending.indexOf(next), 1);\n }\n\n const declarations = ordered.map((entry) => {\n const name = identifier(entry.modelName);\n const fields = entry.fields;\n // A reference is a relation, whose key column is `<relation>Id`.\n const columnKey = (key: string): string =>\n fields[key]?.references ? `${relationOf(key)}Id` : key;\n // A single-field index the table declares (device-authorization's\n // unique `userCode`) is the column's own `.unique` or `.index`.\n const single = new Map<string, boolean>();\n const composite: NonNullable<Tables[string][\"indexes\"]>[number][] = [];\n\n for (const definition of entry.indexes ?? []) {\n const [only, ...others] = definition.fields;\n\n if (only !== undefined && !others.length && Object.hasOwn(fields, only)) {\n single.set(\n only,\n single.get(only) === true || definition.unique === true,\n );\n } else {\n composite.push(definition);\n }\n }\n\n const targets = Object.values(fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(fields).map(([key, field]) => {\n // The SQL name better-auth was given, whenever it is not the key: it\n // is the column's name under either casing.\n const sqlName =\n field.fieldName && field.fieldName !== key\n ? field.fieldName\n : undefined;\n const unique = field.unique === true || single.get(key) === true;\n const reference = field.references;\n\n if (reference) {\n const target = nameOf(reference.model);\n const relation = relationOf(key);\n\n const clash = [relation, `${relation}Id`].find(\n (other) => other !== key && Object.hasOwn(fields, other),\n );\n\n if (clash) {\n throw new Error(\n `symmetria: ${entry.modelName}.${key} references ${target} and becomes the relation \"${relation}\" with the key \"${relation}Id\", but ${entry.modelName} has another field \"${clash}\"; rename one of the two`,\n );\n }\n\n // A key that does not end in `Id` keeps its own SQL name; the\n // relation would otherwise call it `<relation>_id`.\n const column =\n sqlName ??\n (relation === key\n ? options.casing === \"preserve\"\n ? key\n : snakeCase(key)\n : undefined);\n const keyColumn =\n column === undefined ? \"\" : `.column(${JSON.stringify(column)})`;\n // A reference to a field other than the id names it.\n const targetFields = models.find(\n (model) => model.modelName === target,\n )?.fields;\n const targetKey =\n reference.field === \"id\" ||\n !targetFields ||\n Object.hasOwn(targetFields, reference.field)\n ? reference.field\n : (Object.entries(targetFields).find(\n ([, candidate]) => candidate.fieldName === reference.field,\n )?.[0] ?? reference.field);\n const by =\n targetKey === \"id\"\n ? \"\"\n : `.by(${JSON.stringify(targetFields?.[targetKey]?.references ? `${relationOf(targetKey)}Id` : targetKey)})`;\n // better-auth's own migrations cascade when a reference names no\n // action. They give a key no default, so its SET DEFAULT sets NULL:\n // SET NULL for an optional key, a refused delete for a required one.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\" ||\n (reference.onDelete === \"set default\" &&\n field.required === false)\n ? \"setNull\"\n : reference.onDelete === \"no action\" ||\n reference.onDelete === \"set default\"\n ? \"noAction\"\n : undefined;\n const nullable = field.required === false || action === \"setNull\";\n const self = target === entry.modelName;\n const shared = targets.filter((other) => other === target).length > 1;\n\n // Two keys to one table need names for their reverse sides; NO\n // ACTION is spelled on the reference itself.\n if (shared || self || action === \"noAction\") {\n if (self) {\n builders.add(\"self\");\n }\n\n const inverse =\n shared || self\n ? `.inverse(${JSON.stringify(`${name}By${relation[0]!.toUpperCase()}${relation.slice(1)}`)})`\n : \"\";\n\n return ` ${propertyOf(relation)}: ${self ? \"self\" : identifier(target)}${by}${keyColumn}${nullable ? \".nullable\" : \"\"}${unique ? \".unique\" : \".index\"}${action ? `.onDelete.${action}` : \"\"}${inverse},`;\n }\n\n const claim = nullable ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${propertyOf(relation)}: ${claim}(${identifier(target)})${action ? `.${action}` : \"\"}${unique ? \".unique\" : \"\"}${by}${keyColumn},`;\n }\n\n let type: string;\n\n if (Array.isArray(field.type)) {\n builders.add(\"oneOf\");\n type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(\", \")})`;\n } else if (field.type === \"number\") {\n type = field.bigint ? \"bigint\" : \"int\";\n } else {\n type = COLUMN_TYPES[field.type as string] ?? \"text\";\n }\n\n builders.add(type.split(/[.(]/)[0]!);\n\n const fallback = field.defaultValue;\n const literal =\n typeof fallback === \"string\" ||\n typeof fallback === \"number\" ||\n typeof fallback === \"boolean\"\n ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})`\n : \"\";\n const indexed = (field.index === true || single.has(key)) && !unique;\n\n return ` ${propertyOf(key)}: ${type}${sqlName ? `.named(${JSON.stringify(sqlName)})` : \"\"}${field.required === false ? \".nullable\" : \"\"}${unique ? \".unique\" : \"\"}${indexed ? \".index\" : \"\"}${literal},`;\n });\n\n if (composite.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${name} = table({`,\n \" id: text,\",\n ...lines,\n composite.length\n ? `}).indexes((${name}) => ({\\n${composite\n .map(\n (definition) =>\n ` ${propertyOf(definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase()))}: index(${definition.fields\n .map((field) => {\n const key = columnKey(field);\n\n return propertyOf(key) === key\n ? `${name}.${key}`\n : `${name}[${JSON.stringify(key)}]`;\n })\n .join(\", \")})${definition.unique ? \".unique\" : \"\"},`,\n )\n .join(\"\\n\")}\\n}));`\n : \"});\",\n ].join(\"\\n\");\n });\n\n return [\n \"// Written by `auth generate` through symmetria/better-auth.\",\n \"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).\",\n `import { ${[...builders].sort().join(\", \")} } from \"symmetria\";`,\n \"\",\n declarations.join(\"\\n\\n\"),\n \"\",\n `export const authTables = { ${ordered\n .map((entry) => {\n const name = identifier(entry.modelName);\n\n return name === entry.modelName\n ? name\n : `${JSON.stringify(entry.modelName)}: ${name}`;\n })\n .join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\n\nconst SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);\nconst SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);\n\n/**\n * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a\n * `$scope()` of it) whose schema holds the auth tables; better-auth's own\n * transactions run inside `db.$transaction`.\n */\nexport const symmetriaAdapter = (\n db: object,\n options: SymmetriaAdapterOptions = {},\n) => {\n // What better-auth hands the adapter, kept for the adapters built around a transaction.\n let authOptions: BetterAuthOptions | undefined;\n // Each table's column keys, read once, each with the labels of an enum\n // column. The keys tell a reference written as a relation (`requestedById`)\n // from one written as a plain column (`requestedBy`), as modules that\n // earlier versions of `auth generate` wrote declare it, so those modules\n // keep working.\n let columns: ReadonlyMap<string, Labels> | undefined;\n const columnsOf = (model: string): Labels | undefined => {\n columns ??= new Map(\n ((db as Loose).$snapshot?.()?.tables ?? []).map((table: Loose) => [\n table.name,\n new Map(\n table.columns.map((column: Loose) => [\n column.name,\n column.enumerationValues,\n ]),\n ),\n ]),\n );\n\n return columns.get(model);\n };\n\n const build = (connection: Loose): ReturnType<typeof createAdapterFactory> =>\n createAdapterFactory({\n config: {\n adapterId: \"symmetria\",\n adapterName: \"Symmetria\",\n usePlural: options.usePlural ?? false,\n debugLogs: options.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsJSON: true,\n supportsArrays: true,\n // Ids are text columns better-auth fills; `generateId: \"serial\"` is\n // refused when better-auth starts rather than at the first insert.\n supportsNumericIds: false,\n transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: ({\n getDefaultFieldName,\n getDefaultModelName,\n getFieldAttributes,\n getFieldName,\n schema,\n }) => {\n const table = (model: string) => {\n const handle = member(connection, model);\n\n if (!handle) {\n throw new Error(\n `symmetria: better-auth uses a table \"${model}\" that the schema does not have; run \\`npx auth generate\\` and add it`,\n );\n }\n\n return handle;\n };\n // better-auth's fields of a model, by key.\n const fieldsOf = (model: string): Record<string, Loose> => {\n try {\n return schema[getDefaultModelName(model)]?.fields ?? {};\n } catch {\n // Not one of better-auth's models.\n return {};\n }\n };\n // A reference field the table holds as a relation's key column\n // `<field>Id`: `requestedBy` is the relation `requestedBy` and the\n // column `requestedById`. (`userId` is the relation `user` and keeps\n // its key.)\n const relationKeys = new Map<string, ReadonlyMap<string, string>>();\n const relationKeysOf = (model: string): ReadonlyMap<string, string> => {\n let keys = relationKeys.get(model);\n\n if (!keys) {\n const present = columnsOf(model);\n\n keys = new Map(\n Object.entries(fieldsOf(model)).flatMap(([key, field]) =>\n field.references &&\n present &&\n !present.has(key) &&\n present.has(`${key}Id`)\n ? [[key, `${key}Id`] as const]\n : [],\n ),\n );\n relationKeys.set(model, keys);\n }\n\n return keys;\n };\n // The tables are keyed by better-auth's field names (`emailVerified`).\n // It hands over rows and clauses by each field's database name\n // instead (`fields: { emailVerified: \"email_verified\" }`), and that\n // name may be another field's key: under\n // `fields: { image: \"name\", name: \"full_name\" }` the value sent as\n // `name` is the picture. So a database name is looked up among the\n // database names, and is a key only when no field is stored under it.\n const storedNames = new Map<string, ReadonlyMap<string, string>>();\n const fieldOfStored = (model: string, name: string): string => {\n let names = storedNames.get(model);\n\n if (!names) {\n names = new Map(\n Object.entries(fieldsOf(model)).map(([key, field]) => [\n field.fieldName || key,\n key,\n ]),\n );\n storedNames.set(model, names);\n }\n\n return names.get(name) ?? name;\n };\n // The table's key of a field named as better-auth's own code names it\n // (a select, a sort): by its key, or failing that its database name.\n const keyOf = (model: string, field: string): string => {\n let key: string;\n\n try {\n key = getDefaultFieldName({ model, field });\n } catch {\n return field;\n }\n\n return relationKeysOf(model).get(key) ?? key;\n };\n const typeOf = (\n model: string,\n field: string,\n ): Field[\"type\"] | undefined => {\n try {\n return getFieldAttributes({ model, field }).type;\n } catch {\n return undefined;\n }\n };\n // The values of a write under the table's keys.\n const keyed = (model: string, data: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(data).map(([name, value]) => {\n // A value outside an enum column's labels is PostgreSQL's to\n // refuse: the database may hold a label this schema lacks.\n return [keyOf(model, fieldOfStored(model, name)), value];\n }),\n );\n // A key of the table that is one of better-auth's fields (`name`, `userId`).\n const isField = (model: string, key: string): boolean =>\n key === \"id\" || Object.hasOwn(fieldsOf(model), key);\n // The better-auth field a key of the table holds, if any.\n const fieldOf = (model: string, key: string): string | undefined => {\n if (isField(model, key)) {\n return key;\n }\n\n const field = key.slice(0, -2);\n\n return key.endsWith(\"Id\") && relationKeysOf(model).get(field) === key\n ? field\n : undefined;\n };\n // A `bigint` column (`rateLimit.lastRequest`) reads as a bigint;\n // better-auth types its number fields as numbers, so a safe integer\n // goes back as one.\n const output = (model: string, field: string, value: unknown) =>\n typeof value === \"bigint\" &&\n value >= SAFE_MIN &&\n value <= SAFE_MAX &&\n typeOf(model, field) === \"number\"\n ? Number(value)\n : value;\n // Rows go back under better-auth's database names. A column of the\n // application's own (`plan`) is not a better-auth field: it keeps its\n // key, and a field's value wins over it when the two names meet\n // (`fields: { name: \"nickname\" }` next to an app column `nickname`).\n const fielded = (\n model: string,\n row: Record<string, unknown> | null,\n ) => {\n if (!row) {\n return null;\n }\n\n const own: [string, unknown][] = [];\n const fields: [string, unknown][] = [];\n\n for (const [key, value] of Object.entries(row)) {\n const field = fieldOf(model, key);\n\n if (field === undefined) {\n own.push([key, value]);\n } else {\n fields.push([\n getFieldName({ model, field }),\n output(model, field, value),\n ]);\n }\n }\n\n return Object.fromEntries([...own, ...fields]);\n };\n const where = (\n model: string,\n clauses: readonly CleanedWhere[] | undefined,\n ): KeyedWhere[] =>\n (clauses ?? []).map((clause) => {\n const field = fieldOfStored(model, clause.field);\n const key = keyOf(model, field);\n const value = comparable(\n typeOf(model, field),\n clause.value,\n ) as CleanedWhere[\"value\"];\n const labels = columnsOf(model)?.get(key);\n\n return {\n ...clause,\n model,\n key,\n value,\n // An enum column compares as its text, except where the answer\n // is the same and the enum's own comparison can use an index:\n // equality with values that are all labels of it.\n textual:\n labels !== undefined &&\n !(\n EQUALITY.has(clause.operator ?? \"eq\") &&\n [value]\n .flat()\n .every(\n (item) =>\n item === null ||\n item === undefined ||\n labels.includes(item as string),\n )\n ),\n };\n });\n // better-auth's sort: by the column, and by an enum column's text.\n const ordering = (\n model: string,\n sortBy: { field: string; direction: \"asc\" | \"desc\" },\n ) => {\n const key = keyOf(model, sortBy.field);\n\n return columnsOf(model)?.get(key)\n ? (row: Loose) =>\n textOf(columnOf(row, key, sortBy.field))[\n sortBy.direction === \"desc\" ? \"descending\" : \"ascending\"\n ]\n : { [key]: sortBy.direction };\n };\n // A read of the whole row, or of the fields better-auth selects.\n const read = (\n model: string,\n select: readonly string[] | undefined,\n query: object,\n ) =>\n select?.length\n ? table(model)(\n (row: Loose) =>\n Object.fromEntries(\n select.map((field) => {\n const key = keyOf(model, field);\n\n return [key, columnOf(row, key, field)];\n }),\n ),\n query,\n )\n : table(model)(query);\n // An UPDATE or DELETE without a filter is refused unless spelled\n // out; better-auth means every row when it sends none.\n const filtered = (\n model: string,\n mutation: Loose,\n clauses: readonly CleanedWhere[] | undefined,\n ) =>\n clauses?.length\n ? mutation.where(filter(where(model, clauses)))\n : mutation.all();\n // The condition of a write to one row, as better-auth's SQL adapters\n // write it: the first row the filter finds, and the filter itself,\n // which the write tests against the row as it then is. A concurrent\n // change that breaks the filter leaves the row alone, and of two\n // concurrent writers of one row the second sees the first's result.\n const single = (\n handle: Loose,\n model: string,\n clauses: readonly CleanedWhere[] | undefined,\n ) => {\n const keyedWhere = where(model, clauses);\n const condition = keyedWhere.length ? filter(keyedWhere) : undefined;\n\n return (target: Loose) => [\n ...(condition ? [condition(target)] : []),\n columnOf(target, \"id\", \"id\").in(\n handle((first: Loose) => ({ id: first.id }), {\n where: condition,\n limit: 1,\n }),\n ),\n ];\n };\n // A filter that holds for every row (`not_in` an empty list, `ne`\n // null on a required field) is refused like a missing where().\n const refusing = async (\n method: string,\n model: string,\n run: () => Loose,\n ): Promise<Loose> => {\n try {\n return await run();\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"leaves no condition\")\n ) {\n throw new Error(\n `symmetria: better-auth's ${method}() on \"${model}\" has a where that holds for every row (such as not_in an empty list, or ne null on a required field), so the adapter refuses it rather than write every row; call ${method}() without a where to write every row`,\n { cause: error },\n );\n }\n\n throw error;\n }\n };\n\n return {\n create: async ({ model, data }) =>\n fielded(\n model,\n await table(model).insert(keyed(model, data)).returning(),\n ) as never,\n\n findOne: async ({ model, where: clauses, select }) =>\n fielded(\n model,\n await read(model, select, {\n where: filter(where(model, clauses)),\n limit: 1,\n }).first(),\n ) as never,\n\n findMany: async ({\n model,\n where: clauses,\n limit,\n offset,\n sortBy,\n select,\n }) =>\n (\n await read(model, select, {\n where: filter(where(model, clauses)),\n limit,\n offset,\n orderBy: sortBy ? ordering(model, sortBy) : undefined,\n })\n ).map((row: Record<string, unknown>) => fielded(model, row)),\n\n count: ({ model, where: clauses }) =>\n table(model)({ where: filter(where(model, clauses)) }).count(),\n\n update: async ({ model, where: clauses, update }) => {\n const [row] = await refusing(\"update\", model, () =>\n filtered(\n model,\n table(model).update(\n keyed(model, update as Record<string, unknown>),\n ),\n clauses,\n ).returning(),\n );\n\n return fielded(model, row ?? null) as never;\n },\n\n updateMany: async ({ model, where: clauses, update }) =>\n (\n await refusing(\"updateMany\", model, () =>\n filtered(\n model,\n table(model).update(keyed(model, update)),\n clauses,\n ),\n )\n ).affectedRows,\n\n delete: async ({ model, where: clauses }) => {\n await refusing(\"delete\", model, () =>\n filtered(model, table(model).delete(), clauses),\n );\n },\n\n deleteMany: async ({ model, where: clauses }) =>\n (\n await refusing(\"deleteMany\", model, () =>\n filtered(model, table(model).delete(), clauses),\n )\n ).affectedRows,\n\n // One row at most, deleted and returned in one statement while\n // the filter holds for it: the DELETE decides which of two\n // concurrent callers gets the row, and the other gets null.\n consumeOne: async ({ model, where: clauses }) => {\n const handle = table(model);\n const [row] = await handle\n .delete()\n .where(single(handle, model, clauses))\n .returning();\n\n return fielded(model, row ?? null) as never;\n },\n\n // One row, changed while the filter holds for it. A NULL counter\n // counts from 0, as better-auth's own fallback does.\n incrementOne: async ({ model, where: clauses, increment, set }) => {\n const handle = table(model);\n const [row] = await handle\n .update((current: Loose) => ({\n ...keyed(model, set ?? {}),\n ...Object.fromEntries(\n Object.entries(increment).map(([name, delta]) => {\n const key = keyOf(model, fieldOfStored(model, name));\n\n return [\n key,\n (coalesce as Loose)(columnOf(current, key, name), 0).plus(\n delta,\n ),\n ];\n }),\n ),\n }))\n .where(single(handle, model, clauses))\n .returning();\n\n return fielded(model, row ?? null) as never;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables, {\n usePlural: options.usePlural ?? false,\n casing: (db as Loose).$snapshot?.()?.casing,\n }),\n path: file ?? \"./auth-schema.ts\",\n overwrite: true,\n }),\n };\n },\n });\n\n const adapter = build(db);\n\n return (betterAuthOptions: BetterAuthOptions) => {\n authOptions = betterAuthOptions;\n\n return adapter(betterAuthOptions);\n };\n};\n"],"mappings":";;;AAwDA,MAAM,cAAc,UAClB,OAAO,KAAK,CAAC,CAAC,QAAQ,YAAY,cAAc,KAAK,WAAW;;AAMlE,MAAM,2BAAgC,IAAI,IAAI;CAAC;CAAM;CAAM;CAAM;AAAQ,CAAC;;;;;;;AAgB1E,MAAM,UAAU,WACd,iBAAiB,OAAO,OAAO,kBAAkB,CAAC;;AAGpD,MAAM,UAAU,QAAe,QAAuB;CACpD,MAAM,QAAQ,OAAO;CAErB,OAAO,UAAW,OAAO,UAAoB,OAAO,KAAA,IAAY;AAClE;;AAGA,MAAM,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