symmetria 3.5.0 → 3.7.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 (99) hide show
  1. package/README.md +34 -28
  2. package/dist/better-auth.d.ts +3 -1
  3. package/dist/better-auth.js +261 -54
  4. package/dist/better-auth.js.map +1 -1
  5. package/dist/{binding-Dli_0DsL.js → binding-evmthxTh.js} +3 -3
  6. package/dist/binding-evmthxTh.js.map +1 -0
  7. package/dist/bun.d.ts +2 -2
  8. package/dist/bun.js +32 -13
  9. package/dist/bun.js.map +1 -1
  10. package/dist/cohere.d.ts +3 -2
  11. package/dist/cohere.js +4 -3
  12. package/dist/cohere.js.map +1 -1
  13. package/dist/{compile-C4NC4mYL.js → compile-tTAzzMes.js} +170 -55
  14. package/dist/compile-tTAzzMes.js.map +1 -0
  15. package/dist/{core-CFWazQET.js → core-DL4rAoIx.js} +297 -184
  16. package/dist/core-DL4rAoIx.js.map +1 -0
  17. package/dist/driver.d.ts +3 -3
  18. package/dist/driver.js +2 -2
  19. package/dist/{errors-D7nAgODm.js → errors-CLFkJWgJ.js} +13 -8
  20. package/dist/errors-CLFkJWgJ.js.map +1 -0
  21. package/dist/google.d.ts +3 -2
  22. package/dist/google.js +4 -3
  23. package/dist/google.js.map +1 -1
  24. package/dist/http-BHV8rkKW.d.ts +16 -0
  25. package/dist/http-BWqJ9rei.js +75 -0
  26. package/dist/http-BWqJ9rei.js.map +1 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +4467 -735
  29. package/dist/index.js.map +1 -1
  30. package/dist/{inspection-5zJQONLh.js → inspection-lTMOK6ty.js} +4 -4
  31. package/dist/{inspection-5zJQONLh.js.map → inspection-lTMOK6ty.js.map} +1 -1
  32. package/dist/internal.d.ts +6 -2
  33. package/dist/internal.js +6 -5
  34. package/dist/jina.d.ts +3 -2
  35. package/dist/jina.js +11 -8
  36. package/dist/jina.js.map +1 -1
  37. package/dist/metadata-kSK6_Ygx.js +148 -0
  38. package/dist/metadata-kSK6_Ygx.js.map +1 -0
  39. package/dist/mistral.d.ts +3 -2
  40. package/dist/mistral.js +9 -6
  41. package/dist/mistral.js.map +1 -1
  42. package/dist/ollama.d.ts +3 -2
  43. package/dist/ollama.js +40 -9
  44. package/dist/ollama.js.map +1 -1
  45. package/dist/openai.d.ts +3 -2
  46. package/dist/openai.js +4 -3
  47. package/dist/openai.js.map +1 -1
  48. package/dist/opentelemetry.d.ts +4 -3
  49. package/dist/opentelemetry.js +432 -61
  50. package/dist/opentelemetry.js.map +1 -1
  51. package/dist/{pg-CGgCDyKe.js → pg-CWyQOkxm.js} +44 -21
  52. package/dist/pg-CWyQOkxm.js.map +1 -0
  53. package/dist/{pg-BoYrQZ-z.d.ts → pg-IXwZIFh2.d.ts} +3 -3
  54. package/dist/pg.d.ts +3 -3
  55. package/dist/pg.js +2 -2
  56. package/dist/{pool-BGAPbBOW.js → pool-CEeO5spd.js} +93 -10
  57. package/dist/pool-CEeO5spd.js.map +1 -0
  58. package/dist/{pool-7vV2Kz6X.d.ts → pool-wSI6eeqM.d.ts} +2 -2
  59. package/dist/{profiling-OwcSXK1S.js → profiling-CeH3c42X.js} +120 -37
  60. package/dist/profiling-CeH3c42X.js.map +1 -0
  61. package/dist/search-0TyudCVL.js +111 -0
  62. package/dist/search-0TyudCVL.js.map +1 -0
  63. package/dist/search-g9i_87Fs.js +394 -0
  64. package/dist/search-g9i_87Fs.js.map +1 -0
  65. package/dist/search.d.ts +1 -1
  66. package/dist/search.js +1 -1
  67. package/dist/{table-Dy0lctYU.js → table-Jb2bOypw.js} +226 -72
  68. package/dist/table-Jb2bOypw.js.map +1 -0
  69. package/dist/timestamp-key-MxtHruRY.js +26 -0
  70. package/dist/timestamp-key-MxtHruRY.js.map +1 -0
  71. package/dist/{types-DceSuhlk.js → types-BKbG6MO1.js} +372 -20
  72. package/dist/types-BKbG6MO1.js.map +1 -0
  73. package/dist/{types-BwMsRia9.d.ts → types-DNpNC7HQ.d.ts} +256 -57
  74. package/dist/{values-BheIqXI2.js → values-CkYX-ZMl.js} +3 -3
  75. package/dist/values-CkYX-ZMl.js.map +1 -0
  76. package/dist/vector.d.ts +1 -1
  77. package/dist/vector.js +2 -2
  78. package/dist/voyage.d.ts +3 -2
  79. package/dist/voyage.js +14 -10
  80. package/dist/voyage.js.map +1 -1
  81. package/package.json +1 -1
  82. package/dist/binding-Dli_0DsL.js.map +0 -1
  83. package/dist/compile-C4NC4mYL.js.map +0 -1
  84. package/dist/core-CFWazQET.js.map +0 -1
  85. package/dist/errors-D7nAgODm.js.map +0 -1
  86. package/dist/freeze-D2-KMR2m.js +0 -12
  87. package/dist/freeze-D2-KMR2m.js.map +0 -1
  88. package/dist/http-o1fpnTNy.js +0 -33
  89. package/dist/http-o1fpnTNy.js.map +0 -1
  90. package/dist/pg-CGgCDyKe.js.map +0 -1
  91. package/dist/pool-BGAPbBOW.js.map +0 -1
  92. package/dist/profiling-OwcSXK1S.js.map +0 -1
  93. package/dist/search-DZQ8afs5.js +0 -174
  94. package/dist/search-DZQ8afs5.js.map +0 -1
  95. package/dist/search-ks_yELtx.js +0 -47
  96. package/dist/search-ks_yELtx.js.map +0 -1
  97. package/dist/table-Dy0lctYU.js.map +0 -1
  98. package/dist/types-DceSuhlk.js.map +0 -1
  99. package/dist/values-BheIqXI2.js.map +0 -1
package/README.md CHANGED
@@ -179,10 +179,11 @@ const page = feed({ limit: 10 });
179
179
 
180
180
  `join`, `innerJoin` and `leftJoin` infer the target and ON condition from a
181
181
  relation or FK column. Smart `join` uses INNER for required forward references
182
- and LEFT for optional/reverse relations. Repeated sources and self-JOINs receive
183
- automatic aliases. Explicit sources use an ON callback; `crossJoin` creates a
184
- Cartesian product. Options-only calls preserve the previous selection; branches
185
- are immutable.
182
+ and LEFT for optional/reverse relations and for a target a `$scope()` filters.
183
+ Repeated sources and self-JOINs receive automatic aliases. Explicit sources use
184
+ an ON callback; a query with its own fields or options joins only as a subquery
185
+ named with `.as("name")`. `crossJoin` creates a Cartesian product. Options-only
186
+ calls preserve the previous selection; branches are immutable.
186
187
 
187
188
  Smart JOINs also use LEFT for junction relations and propagate optional
188
189
  ancestry. `crossJoin` can infer its target from an FK or relation, without an ON
@@ -205,8 +206,8 @@ const feed = db.posts((post) => ({
205
206
  ```
206
207
 
207
208
  `.shape()` stores a synchronous callback and evaluates it on each application. A
208
- projection belongs to its defining table, contains at least one selected field
209
- and has no `$...` controls. Apply options at use sites, for example
209
+ projection belongs to its defining table and selects at least one field; field
210
+ names starting with `$` are reserved. Apply options at use sites, for example
210
211
  `db.users(userCard, { limit: 20 })`. It can be defined on an offline schema and
211
212
  used on its connected or transaction-bound tables. To-one selections are typed
212
213
  as an object or `null`.
@@ -229,11 +230,11 @@ const totals = db.users(({ name, posts }) => ({
229
230
 
230
231
  Plain columns aggregate through properties (`posts.sum.views`); expressions use
231
232
  the callback form. Filters and pagination select input rows before aggregation.
232
- `sum` / `average` return decimal strings or `null`; `minimum` / `maximum`
233
- preserve the column's value type and codec, plus `null`, and order JSON values
234
- as jsonb does (numbers numerically), booleans, `uuid` and `bytea` too. Empty or
235
- all-NULL value inputs produce `null`; `count()` returns `0` and `exists()`
236
- returns `false` for empty inputs.
233
+ `sum` / `average` return decimal strings or `null`. `minimum` / `maximum` keep
234
+ the column's value type and codec, plus `null`, and take any column: booleans,
235
+ `uuid` and `bytea` too, and JSON values, which they order as jsonb does (numbers
236
+ by value). Empty or all-NULL value inputs produce `null`; `count()` returns `0`
237
+ and `exists()` returns `false` for empty inputs.
237
238
 
238
239
  ## Enum mappings
239
240
 
@@ -278,7 +279,8 @@ projection of the same table. UPDATE, WHERE and RETURNING callbacks receive the
278
279
  row directly, including nested-insert RETURNING. Upserts receive the existing
279
280
  row first and the proposed `excluded` row second. `.doUpdate("name")` copies a
280
281
  field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
281
- `.all()` confirms it.
282
+ `.all()` confirms it, and so is one whose filter holds for every row, such as
283
+ `and()` or `notIn([])`.
282
284
 
283
285
  ## Capabilities
284
286
 
@@ -299,10 +301,12 @@ field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
299
301
  iteration; `count()` and `exists()` on any table or filtered source.
300
302
  - Transactions, nested savepoints, isolation options and row locks.
301
303
  - `Transaction<typeof db>` for schema-specific transaction helpers.
302
- - `$scope()` filters for reads, updates and deletes, including related tables,
303
- and checks every row a scoped insert, upsert or update writes, like row-level
304
- security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and prepared
305
- queries bind the current tenant at every execution.
304
+ - `$scope()` filters for reads, updates and deletes, including related and
305
+ joined tables, and checks every row a scoped insert, upsert or update writes,
306
+ like row-level security's `WITH CHECK` (`SYMMETRIA_OUT_OF_SCOPE`); reused and
307
+ prepared queries bind the current tenant at every execution. A scope filter
308
+ that holds for every row, such as `and(tenant && post.tenantId.is(tenant))`
309
+ without a tenant, is refused instead of reading every tenant's rows.
306
310
  - Bigint, decimal-string, Date and custom codecs, including nested JSON results;
307
311
  `smallint`, `real`, `doublePrecision`, `date`, `time`, `interval`, `bytea` and
308
312
  `inet` as first-class builders.
@@ -324,13 +328,13 @@ field from `excluded`. An UPDATE or DELETE without `where()` is refused unless
324
328
  - `table.search()`: hybrid search declared on the table, by words (full text or
325
329
  BM25) and by meaning (embeddings computed on insert), merged in one statement
326
330
  (`symmetria/search`; models from `symmetria/voyage`, `openai`, `cohere`,
327
- `google`, `mistral`, `jina`, `ollama`)
328
- - `symmetria/better-auth`: a better-auth adapter; `auth generate` writes the
329
- auth tables as part of your schema
331
+ `google`, `mistral`, `jina`, `ollama`).
332
+ - `symmetria/better-auth`: a better-auth adapter; `npx auth generate` writes the
333
+ auth tables as part of your schema.
330
334
  - Arrays, full-text search with stored `tsvector` columns, weighted documents,
331
335
  ranking and headlines, pgvector embeddings with distance operators and HNSW
332
- indexes (`symmetria/vector`), typed JSON paths and Standard Schema JSON
333
- validation.
336
+ and IVFFlat indexes (`symmetria/vector`), typed JSON paths and Standard Schema
337
+ JSON validation.
334
338
  - Computed fields, branded IDs, indexes, primary keys and CHECK constraints.
335
339
  - Condition relations (`.relations()`) that join by a predicate without a
336
340
  foreign key, in both directions, invisible to migrations.
@@ -384,13 +388,15 @@ const db = createDatabase({
384
388
  underlying pool options plus `url` and `profiler`.
385
389
 
386
390
  Both adapters return `{ rows, affectedRows }`, read values the same way,
387
- preserve bigint/numeric precision, support nested transactions and pinned
388
- sessions, and drain accepted operations on close. Operations on a transaction or
389
- session run one at a time in call order. Session settings belong to a
390
- connection: use `driver.session()` for multi-statement workflows; its connection
391
- is closed afterwards, so its settings, locks and temporary tables never reach
392
- other queries. For isolated PostgreSQL test schemas, use `testDatabase()` from
393
- `symmetria-kit/testing`, optionally passing a `driver` factory.
391
+ preserve bigint/numeric precision and support nested transactions and pinned
392
+ sessions. On close they refuse new work, end the transactions of open `stream()`
393
+ loops and wait for the other operations they accepted. Operations on a
394
+ transaction or session run one at a time in call order. Session settings belong
395
+ to a connection: use `driver.session()` for multi-statement workflows; its
396
+ connection is closed afterwards, so its settings, locks and temporary tables
397
+ never reach other queries. For isolated PostgreSQL test schemas, use
398
+ `testDatabase()` from `symmetria-kit/testing`, optionally passing a `driver`
399
+ factory.
394
400
 
395
401
  Behind a transaction-mode pooler such as PgBouncer, queries, transactions,
396
402
  streams and prepared queries work on both adapters; pass `prepare: false` to
@@ -33,10 +33,12 @@ type Field = {
33
33
  * Tables come out in an order where each one follows the tables it
34
34
  * references; spread `authTables` into `schema({ ... })`. With `usePlural`
35
35
  * the tables are keyed in the plural (`users`), as the adapter then asks for
36
- * them.
36
+ * them; `casing` is the schema's (`"preserve"` keeps a reference key such as
37
+ * `requestedBy` as its SQL name).
37
38
  */
38
39
  export declare const authSchemaSource: (input: Tables, options?: {
39
40
  readonly usePlural?: boolean;
41
+ readonly casing?: "snake_case" | "preserve";
40
42
  }) => string;
41
43
  /**
42
44
  * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
@@ -1,4 +1,4 @@
1
- import { S as or, d as and, y as not } from "./core-CFWazQET.js";
1
+ import { C as not, E as or, g as coalesce, m as and } from "./core-DL4rAoIx.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}`);
@@ -7,24 +7,55 @@ const member = (target, key) => {
7
7
  const value = target[key];
8
8
  return value === Object.prototype[key] ? void 0 : value;
9
9
  };
10
+ /** The column `key` of a row, for better-auth's field `field`. */
11
+ const columnOf = (row, key, field) => {
12
+ const column = member(row, key);
13
+ if (!column) throw new Error(`symmetria: better-auth asked for field "${field}", which the table does not have`);
14
+ return column;
15
+ };
16
+ /**
17
+ * A where value in the form its field's column compares. better-auth passes
18
+ * request values on as they come (the admin plugin's `filterValue: 1984` for
19
+ * a text field): node-postgres sends a number untyped, which PostgreSQL reads
20
+ * as text, while Bun.SQL binds it as an integer and the comparison fails, so a
21
+ * string field gets a string on every driver. A list for a boolean field
22
+ * reads "true" and "false" as better-auth reads a single value.
23
+ */
24
+ const comparable = (type, value) => {
25
+ if (Array.isArray(value)) return value.map((item) => comparable(type, item));
26
+ if ((type === "string" || Array.isArray(type)) && (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean")) return String(value);
27
+ return type === "boolean" && (value === "true" || value === "false") ? value === "true" : value;
28
+ };
29
+ const none = (column) => column.in([]);
10
30
  const predicate = (row, clause) => {
11
- const column = member(row, clause.key);
12
- if (!column) throw new Error(`symmetria: better-auth asked for field "${clause.field}", which the table does not have`);
13
- const insensitive = clause.mode === "insensitive" && typeof clause.value === "string";
14
- const insensitiveList = clause.mode === "insensitive" && Array.isArray(clause.value) && clause.value.length > 0 && clause.value.every((value) => typeof value === "string");
31
+ const column = columnOf(row, clause.key, clause.field);
32
+ const { value } = clause;
33
+ const missing = value === void 0 || value === null;
34
+ const insensitive = clause.mode === "insensitive" && typeof value === "string";
15
35
  const pattern = (text) => insensitive ? column.ilike(text) : column.like(text);
16
36
  switch (clause.operator) {
17
- case "ne": return insensitive ? not(column.ilike(escapeLike(clause.value))) : column.isNot(clause.value);
18
- case "in": return insensitiveList ? or(...clause.value.map((value) => column.ilike(escapeLike(value)))) : column.in(clause.value);
19
- case "not_in": return insensitiveList ? and(...clause.value.map((value) => not(column.ilike(escapeLike(value))))) : column.notIn(clause.value);
20
- case "gt": return column.above(clause.value);
21
- case "gte": return column.atLeast(clause.value);
22
- case "lt": return column.below(clause.value);
23
- case "lte": return column.atMost(clause.value);
24
- case "contains": return pattern(`%${escapeLike(clause.value)}%`);
25
- case "starts_with": return pattern(`${escapeLike(clause.value)}%`);
26
- case "ends_with": return pattern(`%${escapeLike(clause.value)}`);
27
- default: return insensitive ? column.ilike(escapeLike(clause.value)) : column.is(clause.value);
37
+ case "ne":
38
+ if (value === null) return column.isNot(null);
39
+ return value === void 0 ? none(column) : insensitive ? not(column.ilike(escapeLike(value))) : column.isNot(value);
40
+ case "in":
41
+ case "not_in": {
42
+ const list = Array.isArray(value) ? value : [value];
43
+ const present = list.filter((item) => item !== void 0 && item !== null);
44
+ const insensitiveList = clause.mode === "insensitive" && present.length > 0 && present.every((item) => typeof item === "string");
45
+ if (clause.operator === "in") return insensitiveList ? or(...present.map((item) => column.ilike(escapeLike(item)))) : column.in(present);
46
+ if (present.length < list.length) return none(column);
47
+ return insensitiveList ? and(...present.map((item) => not(column.ilike(escapeLike(item))))) : column.notIn(present);
48
+ }
49
+ case "gt": return missing ? none(column) : column.above(value);
50
+ case "gte": return missing ? none(column) : column.atLeast(value);
51
+ case "lt": return missing ? none(column) : column.below(value);
52
+ case "lte": return missing ? none(column) : column.atMost(value);
53
+ case "contains": return missing ? none(column) : pattern(`%${escapeLike(value)}%`);
54
+ case "starts_with": return missing ? none(column) : pattern(`${escapeLike(value)}%`);
55
+ case "ends_with": return missing ? none(column) : pattern(`%${escapeLike(value)}`);
56
+ default:
57
+ if (value === null) return column.is(null);
58
+ return value === void 0 ? none(column) : insensitive ? column.ilike(escapeLike(value)) : column.is(value);
28
59
  }
29
60
  };
30
61
  /** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */
@@ -42,13 +73,90 @@ const COLUMN_TYPES = {
42
73
  "string[]": "text.array",
43
74
  "number[]": "int.array"
44
75
  };
45
- const snakeCase = (name) => name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
76
+ /** A key's SQL name under schema()'s default casing (`requestedBy` → `requested_by`). */
77
+ const snakeCase = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
78
+ /** Names a module cannot declare: JavaScript's reserved words and what it imports. */
79
+ const TAKEN = /* @__PURE__ */ new Set([
80
+ "arguments",
81
+ "await",
82
+ "break",
83
+ "case",
84
+ "catch",
85
+ "class",
86
+ "const",
87
+ "continue",
88
+ "debugger",
89
+ "default",
90
+ "delete",
91
+ "do",
92
+ "else",
93
+ "enum",
94
+ "eval",
95
+ "export",
96
+ "extends",
97
+ "false",
98
+ "finally",
99
+ "for",
100
+ "function",
101
+ "if",
102
+ "implements",
103
+ "import",
104
+ "in",
105
+ "instanceof",
106
+ "interface",
107
+ "let",
108
+ "new",
109
+ "null",
110
+ "package",
111
+ "private",
112
+ "protected",
113
+ "public",
114
+ "return",
115
+ "static",
116
+ "super",
117
+ "switch",
118
+ "this",
119
+ "throw",
120
+ "true",
121
+ "try",
122
+ "typeof",
123
+ "undefined",
124
+ "var",
125
+ "void",
126
+ "while",
127
+ "with",
128
+ "yield",
129
+ "Infinity",
130
+ "NaN",
131
+ "authTables",
132
+ "bigint",
133
+ "bool",
134
+ "index",
135
+ "int",
136
+ "jsonb",
137
+ "maybe",
138
+ "one",
139
+ "oneOf",
140
+ "self",
141
+ "table",
142
+ "text",
143
+ "timestamptz"
144
+ ]);
145
+ /** A JavaScript name for a model: `auth-user` → `authUser`, `default` → `defaultTable`. */
146
+ const identifierOf = (name) => {
147
+ const joined = name.split(/[^\p{ID_Continue}$]+/u).filter(Boolean).map((word, position) => position ? `${word[0].toUpperCase()}${word.slice(1)}` : word).join("");
148
+ const named = /^[\p{ID_Start}$_]/u.test(joined) ? joined : `_${joined}`;
149
+ return TAKEN.has(named) ? `${named}Table` : named;
150
+ };
151
+ /** The relation a reference field becomes: `userId` → `user`, `requestedBy` stays. */
152
+ const relationOf = (key) => key.length > 2 && key.endsWith("Id") ? key.slice(0, -2) : key;
46
153
  /**
47
154
  * The auth tables as a Symmetria schema module, for `npx auth generate`.
48
155
  * Tables come out in an order where each one follows the tables it
49
156
  * references; spread `authTables` into `schema({ ... })`. With `usePlural`
50
157
  * the tables are keyed in the plural (`users`), as the adapter then asks for
51
- * them.
158
+ * them; `casing` is the schema's (`"preserve"` keeps a reference key such as
159
+ * `requestedBy` as its SQL name).
52
160
  */
53
161
  const authSchemaSource = (input, options = {}) => {
54
162
  const tables = options.usePlural ? Object.fromEntries(Object.entries(input).map(([model, entry]) => [model, {
@@ -58,6 +166,17 @@ const authSchemaSource = (input, options = {}) => {
58
166
  const builders = /* @__PURE__ */ new Set(["table", "text"]);
59
167
  const models = Object.values(tables);
60
168
  const nameOf = (model) => tables[model]?.modelName ?? models.find((entry) => entry.modelName === model)?.modelName ?? model;
169
+ const identifiers = /* @__PURE__ */ new Map();
170
+ const used = /* @__PURE__ */ new Set();
171
+ for (const plain of [true, false]) for (const { modelName } of models) {
172
+ const base = identifierOf(modelName);
173
+ if (base === modelName !== plain || identifiers.has(modelName)) continue;
174
+ let name = base;
175
+ for (let count = 2; used.has(name); count++) name = `${base}${count}`;
176
+ used.add(name);
177
+ identifiers.set(modelName, name);
178
+ }
179
+ const identifier = (modelName) => identifiers.get(modelName) ?? modelName;
61
180
  const ordered = [];
62
181
  const pending = [...models];
63
182
  while (pending.length) {
@@ -66,23 +185,43 @@ const authSchemaSource = (input, options = {}) => {
66
185
  pending.splice(pending.indexOf(next), 1);
67
186
  }
68
187
  const declarations = ordered.map((entry) => {
69
- const targets = Object.values(entry.fields).flatMap((field) => field.references ? [nameOf(field.references.model)] : []);
70
- const lines = Object.entries(entry.fields).map(([key, field]) => {
71
- const named = field.fieldName && field.fieldName !== key && field.fieldName !== snakeCase(key) ? `.named(${JSON.stringify(field.fieldName)})` : "";
188
+ const name = identifier(entry.modelName);
189
+ const fields = entry.fields;
190
+ const columnKey = (key) => fields[key]?.references ? `${relationOf(key)}Id` : key;
191
+ const single = /* @__PURE__ */ new Map();
192
+ const composite = [];
193
+ for (const definition of entry.indexes ?? []) {
194
+ const [only, ...others] = definition.fields;
195
+ if (only !== void 0 && !others.length && Object.hasOwn(fields, only)) single.set(only, single.get(only) === true || definition.unique === true);
196
+ else composite.push(definition);
197
+ }
198
+ const targets = Object.values(fields).flatMap((field) => field.references ? [nameOf(field.references.model)] : []);
199
+ const lines = Object.entries(fields).map(([key, field]) => {
200
+ const sqlName = field.fieldName && field.fieldName !== key ? field.fieldName : void 0;
201
+ const unique = field.unique === true || single.get(key) === true;
72
202
  const reference = field.references;
73
- if (reference && reference.field === "id" && key.endsWith("Id")) {
203
+ if (reference) {
74
204
  const target = nameOf(reference.model);
75
- const keyColumn = named ? `.column(${JSON.stringify(field.fieldName)})` : "";
76
- const action = reference.onDelete === void 0 || reference.onDelete === "cascade" ? "cascade" : reference.onDelete === "set null" ? "setNull" : void 0;
77
- const relation = key.slice(0, -2);
205
+ const relation = relationOf(key);
206
+ const clash = [relation, `${relation}Id`].find((other) => other !== key && Object.hasOwn(fields, other));
207
+ if (clash) throw new Error(`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`);
208
+ const column = sqlName ?? (relation === key ? options.casing === "preserve" ? key : snakeCase(key) : void 0);
209
+ const keyColumn = column === void 0 ? "" : `.column(${JSON.stringify(column)})`;
210
+ const targetFields = models.find((model) => model.modelName === target)?.fields;
211
+ const targetKey = reference.field === "id" || !targetFields || Object.hasOwn(targetFields, reference.field) ? reference.field : Object.entries(targetFields).find(([, candidate]) => candidate.fieldName === reference.field)?.[0] ?? reference.field;
212
+ const by = targetKey === "id" ? "" : `.by(${JSON.stringify(targetFields?.[targetKey]?.references ? `${relationOf(targetKey)}Id` : targetKey)})`;
213
+ const action = reference.onDelete === void 0 || reference.onDelete === "cascade" ? "cascade" : reference.onDelete === "set null" || reference.onDelete === "set default" && field.required === false ? "setNull" : reference.onDelete === "no action" || reference.onDelete === "set default" ? "noAction" : void 0;
214
+ const nullable = field.required === false || action === "setNull";
78
215
  const self = target === entry.modelName;
79
- if (targets.filter((name) => name === target).length > 1 || self) {
216
+ const shared = targets.filter((other) => other === target).length > 1;
217
+ if (shared || self || action === "noAction") {
80
218
  if (self) builders.add("self");
81
- return ` ${relation}: ${self ? "self" : target}${keyColumn}${field.required === false || action === "setNull" ? ".nullable" : ""}${field.unique ? ".unique" : ".index"}${action ? `.onDelete.${action}` : ""}.inverse(${JSON.stringify(`${entry.modelName}By${relation[0].toUpperCase()}${relation.slice(1)}`)}),`;
219
+ 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},`;
82
221
  }
83
- const claim = field.required === false || action === "setNull" ? "maybe" : "one";
222
+ const claim = nullable ? "maybe" : "one";
84
223
  builders.add(claim);
85
- return ` ${relation}: ${claim}(${target})${action ? `.${action}` : ""}${field.unique ? ".unique" : ""}${keyColumn},`;
224
+ return ` ${relation}: ${claim}(${identifier(target)})${action ? `.${action}` : ""}${unique ? ".unique" : ""}${by}${keyColumn},`;
86
225
  }
87
226
  let type;
88
227
  if (Array.isArray(field.type)) {
@@ -93,15 +232,15 @@ const authSchemaSource = (input, options = {}) => {
93
232
  builders.add(type.split(/[.(]/)[0]);
94
233
  const fallback = field.defaultValue;
95
234
  const literal = typeof fallback === "string" || typeof fallback === "number" || typeof fallback === "boolean" ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})` : "";
96
- return ` ${key}: ${type}${named}${field.required === false ? ".nullable" : ""}${field.unique ? ".unique" : ""}${field.index && !field.unique ? ".index" : ""}${literal},`;
235
+ 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},`;
97
237
  });
98
- const indexes = (entry.indexes ?? []).filter((definition) => definition.fields.length > 1);
99
- if (indexes.length) builders.add("index");
238
+ if (composite.length) builders.add("index");
100
239
  return [
101
- `export const ${entry.modelName} = table({`,
240
+ `export const ${name} = table({`,
102
241
  " id: text,",
103
242
  ...lines,
104
- indexes.length ? `}).indexes((${entry.modelName}) => ({\n${indexes.map((definition) => ` ${definition.fields.join("_").replace(/_(\w)/g, (_match, letter) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).join(", ")})${definition.unique ? ".unique" : ""},`).join("\n")}\n}));` : "});"
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}));` : "});"
105
244
  ].join("\n");
106
245
  });
107
246
  return [
@@ -111,10 +250,15 @@ const authSchemaSource = (input, options = {}) => {
111
250
  "",
112
251
  declarations.join("\n\n"),
113
252
  "",
114
- `export const authTables = { ${ordered.map((entry) => entry.modelName).join(", ")} };`,
253
+ `export const authTables = { ${ordered.map((entry) => {
254
+ const name = identifier(entry.modelName);
255
+ return name === entry.modelName ? name : `${JSON.stringify(entry.modelName)}: ${name}`;
256
+ }).join(", ")} };`,
115
257
  ""
116
258
  ].join("\n");
117
259
  };
260
+ const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);
261
+ const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
118
262
  /**
119
263
  * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a
120
264
  * `$scope()` of it) whose schema holds the auth tables; better-auth's own
@@ -122,6 +266,11 @@ const authSchemaSource = (input, options = {}) => {
122
266
  */
123
267
  const symmetriaAdapter = (db, options = {}) => {
124
268
  let authOptions;
269
+ let columns;
270
+ const columnsOf = (model) => {
271
+ columns ??= new Map((db.$snapshot?.()?.tables ?? []).map((table) => [table.name, new Set(table.columns.map((column) => column.name))]));
272
+ return columns.get(model);
273
+ };
125
274
  const build = (connection) => createAdapterFactory({
126
275
  config: {
127
276
  adapterId: "symmetria",
@@ -135,21 +284,47 @@ const symmetriaAdapter = (db, options = {}) => {
135
284
  supportsNumericIds: false,
136
285
  transaction: (callback) => connection.$transaction((transaction) => callback(build(transaction)(authOptions ?? {})))
137
286
  },
138
- adapter: ({ getDefaultFieldName, getDefaultModelName, getFieldName, schema }) => {
287
+ adapter: ({ getDefaultFieldName, getDefaultModelName, getFieldAttributes, getFieldName, schema }) => {
139
288
  const table = (model) => {
140
289
  const handle = member(connection, model);
141
290
  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`);
142
291
  return handle;
143
292
  };
293
+ const relationKeys = /* @__PURE__ */ new Map();
294
+ const relationKeysOf = (model) => {
295
+ let keys = relationKeys.get(model);
296
+ if (!keys) {
297
+ 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`]] : []));
303
+ relationKeys.set(model, keys);
304
+ }
305
+ return keys;
306
+ };
144
307
  const keyOf = (model, field) => {
308
+ let key;
145
309
  try {
146
- return getDefaultFieldName({
310
+ key = getDefaultFieldName({
147
311
  model,
148
312
  field
149
313
  });
150
314
  } catch {
151
315
  return field;
152
316
  }
317
+ return relationKeysOf(model).get(key) ?? key;
318
+ };
319
+ const typeOf = (model, field) => {
320
+ try {
321
+ return getFieldAttributes({
322
+ model,
323
+ field
324
+ }).type;
325
+ } catch {
326
+ return;
327
+ }
153
328
  };
154
329
  const keyed = (model, data) => Object.fromEntries(Object.entries(data).map(([field, value]) => [keyOf(model, field), value]));
155
330
  const isField = (model, key) => {
@@ -161,28 +336,51 @@ const symmetriaAdapter = (db, options = {}) => {
161
336
  return false;
162
337
  }
163
338
  };
339
+ const fieldOf = (model, key) => {
340
+ if (isField(model, key)) return key;
341
+ const field = key.slice(0, -2);
342
+ return key.endsWith("Id") && relationKeysOf(model).get(field) === key ? field : void 0;
343
+ };
344
+ const output = (model, field, value) => typeof value === "bigint" && value >= SAFE_MIN && value <= SAFE_MAX && typeOf(model, field) === "number" ? Number(value) : value;
164
345
  const fielded = (model, row) => {
165
346
  if (!row) return null;
166
- const entries = Object.entries(row);
167
- const own = entries.filter(([key]) => !isField(model, key));
168
- const fields = entries.filter(([key]) => isField(model, key)).map(([key, value]) => [getFieldName({
169
- model,
170
- field: key
171
- }), value]);
347
+ const own = [];
348
+ const fields = [];
349
+ for (const [key, value] of Object.entries(row)) {
350
+ const field = fieldOf(model, key);
351
+ if (field === void 0) own.push([key, value]);
352
+ else fields.push([getFieldName({
353
+ model,
354
+ field
355
+ }), output(model, field, value)]);
356
+ }
172
357
  return Object.fromEntries([...own, ...fields]);
173
358
  };
174
359
  const where = (model, clauses) => (clauses ?? []).map((clause) => ({
175
360
  ...clause,
176
- key: keyOf(model, clause.field)
361
+ key: keyOf(model, clause.field),
362
+ value: comparable(typeOf(model, clause.field), clause.value)
177
363
  }));
364
+ const read = (model, select, query) => select?.length ? table(model)((row) => Object.fromEntries(select.map((field) => {
365
+ const key = keyOf(model, field);
366
+ return [key, columnOf(row, key, field)];
367
+ })), query) : table(model)(query);
178
368
  const filtered = (model, mutation, clauses) => clauses?.length ? mutation.where(filter(where(model, clauses))) : mutation.all();
369
+ const refusing = async (method, model, run) => {
370
+ try {
371
+ return await run();
372
+ } catch (error) {
373
+ if (error instanceof Error && error.message.includes("leaves no condition")) throw new Error(`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`, { cause: error });
374
+ throw error;
375
+ }
376
+ };
179
377
  return {
180
378
  create: async ({ model, data }) => fielded(model, await table(model).insert(keyed(model, data)).returning()),
181
- findOne: async ({ model, where: clauses }) => fielded(model, await table(model)({
379
+ findOne: async ({ model, where: clauses, select }) => fielded(model, await read(model, select, {
182
380
  where: filter(where(model, clauses)),
183
381
  limit: 1
184
382
  }).first()),
185
- findMany: async ({ model, where: clauses, limit, offset, sortBy }) => (await table(model)({
383
+ findMany: async ({ model, where: clauses, limit, offset, sortBy, select }) => (await read(model, select, {
186
384
  where: filter(where(model, clauses)),
187
385
  limit,
188
386
  offset,
@@ -190,14 +388,14 @@ const symmetriaAdapter = (db, options = {}) => {
190
388
  })).map((row) => fielded(model, row)),
191
389
  count: ({ model, where: clauses }) => table(model)({ where: filter(where(model, clauses)) }).count(),
192
390
  update: async ({ model, where: clauses, update }) => {
193
- const [row] = await filtered(model, table(model).update(keyed(model, update)), clauses).returning();
391
+ const [row] = await refusing("update", model, () => filtered(model, table(model).update(keyed(model, update)), clauses).returning());
194
392
  return fielded(model, row ?? null);
195
393
  },
196
- updateMany: async ({ model, where: clauses, update }) => (await filtered(model, table(model).update(keyed(model, update)), clauses)).affectedRows,
394
+ updateMany: async ({ model, where: clauses, update }) => (await refusing("updateMany", model, () => filtered(model, table(model).update(keyed(model, update)), clauses))).affectedRows,
197
395
  delete: async ({ model, where: clauses }) => {
198
- await filtered(model, table(model).delete(), clauses);
396
+ await refusing("delete", model, () => filtered(model, table(model).delete(), clauses));
199
397
  },
200
- deleteMany: async ({ model, where: clauses }) => (await filtered(model, table(model).delete(), clauses)).affectedRows,
398
+ deleteMany: async ({ model, where: clauses }) => (await refusing("deleteMany", model, () => filtered(model, table(model).delete(), clauses))).affectedRows,
201
399
  consumeOne: async ({ model, where: clauses }) => {
202
400
  const found = await table(model)({
203
401
  where: filter(where(model, clauses)),
@@ -208,17 +406,26 @@ const symmetriaAdapter = (db, options = {}) => {
208
406
  return fielded(model, row ?? null);
209
407
  },
210
408
  incrementOne: async ({ model, where: clauses, increment, set }) => {
211
- const [row] = await filtered(model, table(model).update((current) => ({
409
+ const handle = table(model);
410
+ const keyedWhere = where(model, clauses);
411
+ const condition = keyedWhere.length ? filter(keyedWhere) : void 0;
412
+ const [row] = await handle.update((current) => ({
212
413
  ...keyed(model, set ?? {}),
213
414
  ...Object.fromEntries(Object.entries(increment).map(([field, delta]) => {
214
415
  const key = keyOf(model, field);
215
- return [key, current[key].plus(delta)];
416
+ return [key, coalesce(columnOf(current, key, field), 0).plus(delta)];
216
417
  }))
217
- })), clauses).returning();
418
+ })).where((target) => [...condition ? [condition(target)] : [], columnOf(target, "id", "id").in(handle((first) => ({ id: first.id }), {
419
+ where: condition,
420
+ limit: 1
421
+ }))]).returning();
218
422
  return fielded(model, row ?? null);
219
423
  },
220
424
  createSchema: async ({ tables, file }) => ({
221
- code: authSchemaSource(tables, { usePlural: options.usePlural ?? false }),
425
+ code: authSchemaSource(tables, {
426
+ usePlural: options.usePlural ?? false,
427
+ casing: db.$snapshot?.()?.casing
428
+ }),
222
429
  path: file ?? "./auth-schema.ts",
223
430
  overwrite: true
224
431
  })