symmetria 2.5.0 → 3.1.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 (58) hide show
  1. package/dist/better-auth.js +3 -3
  2. package/dist/better-auth.js.map +1 -1
  3. package/dist/bun.d.ts +2 -2
  4. package/dist/bun.js +1 -1
  5. package/dist/cohere.d.ts +1 -1
  6. package/dist/cohere.js +1 -1
  7. package/dist/{compile-hFOq0snq.js → compile-Cfv7061C.js} +22 -8
  8. package/dist/compile-Cfv7061C.js.map +1 -0
  9. package/dist/{core-kaO0qvAO.js → core-j8XuMGmY.js} +24 -6
  10. package/dist/core-j8XuMGmY.js.map +1 -0
  11. package/dist/driver.d.ts +3 -3
  12. package/dist/driver.js +1 -1
  13. package/dist/google.d.ts +1 -1
  14. package/dist/google.js +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +289 -140
  17. package/dist/index.js.map +1 -1
  18. package/dist/{inspection-djgix9ya.js → inspection-WNNakwoE.js} +3 -3
  19. package/dist/{inspection-djgix9ya.js.map → inspection-WNNakwoE.js.map} +1 -1
  20. package/dist/internal.d.ts +1 -1
  21. package/dist/internal.js +3 -3
  22. package/dist/jina.d.ts +1 -1
  23. package/dist/jina.js +1 -1
  24. package/dist/mistral.d.ts +1 -1
  25. package/dist/mistral.js +1 -1
  26. package/dist/ollama.d.ts +1 -1
  27. package/dist/ollama.js +1 -1
  28. package/dist/openai.d.ts +1 -1
  29. package/dist/openai.js +1 -1
  30. package/dist/{pg-B5rodRoT.d.ts → pg-CFB1A5bi.d.ts} +9 -3
  31. package/dist/{pg-9c7xlOnS.js → pg-D642sWtx.js} +25 -6
  32. package/dist/pg-D642sWtx.js.map +1 -0
  33. package/dist/pg.d.ts +3 -3
  34. package/dist/pg.js +1 -1
  35. package/dist/{pool-XG_sgock.d.ts → pool-DLmybA--.d.ts} +2 -2
  36. package/dist/{pool-C3RZQz3X.js → pool-dF8wVzv2.js} +14 -9
  37. package/dist/{pool-C3RZQz3X.js.map → pool-dF8wVzv2.js.map} +1 -1
  38. package/dist/{search-jZqgEILM.js → search-D953bVPb.js} +3 -3
  39. package/dist/{search-jZqgEILM.js.map → search-D953bVPb.js.map} +1 -1
  40. package/dist/search.d.ts +1 -1
  41. package/dist/search.js +1 -1
  42. package/dist/{table-BOy3SI0b.js → table-x4L0cE1T.js} +35 -20
  43. package/dist/table-x4L0cE1T.js.map +1 -0
  44. package/dist/{types-BCMCu-EF.js → types-NVB9dmsW.js} +49 -4
  45. package/dist/types-NVB9dmsW.js.map +1 -0
  46. package/dist/{types-C2s_w1LW.d.ts → types-r3vlr_gE.d.ts} +3 -1
  47. package/dist/{values-CInqtWRn.js → values-CnN8eqP3.js} +2 -2
  48. package/dist/{values-CInqtWRn.js.map → values-CnN8eqP3.js.map} +1 -1
  49. package/dist/vector.d.ts +1 -1
  50. package/dist/vector.js +1 -1
  51. package/dist/voyage.d.ts +1 -1
  52. package/dist/voyage.js +1 -1
  53. package/package.json +1 -1
  54. package/dist/compile-hFOq0snq.js.map +0 -1
  55. package/dist/core-kaO0qvAO.js.map +0 -1
  56. package/dist/pg-9c7xlOnS.js.map +0 -1
  57. package/dist/table-BOy3SI0b.js.map +0 -1
  58. package/dist/types-BCMCu-EF.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { _ as not, b as or, l as and } from "./core-kaO0qvAO.js";
1
+ import { _ as not, b as or, l as and } from "./core-j8XuMGmY.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}`);
@@ -160,10 +160,10 @@ const symmetriaAdapter = (db, options = {}) => {
160
160
  return row ?? null;
161
161
  },
162
162
  incrementOne: async ({ model, where, increment, set }) => {
163
- const [row] = await table(model).update((current) => ({
163
+ const [row] = await filtered(table(model).update((current) => ({
164
164
  ...set,
165
165
  ...Object.fromEntries(Object.entries(increment).map(([field, delta]) => [field, current[field].plus(delta)]))
166
- })).where(filter(where)).returning();
166
+ })), where).returning();
167
167
  return row ?? null;
168
168
  },
169
169
  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, 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\nconst predicate = (row: Loose, clause: CleanedWhere) => {\n const column = row[clause.field];\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${clause.field}\", which the table does not have`,\n );\n }\n\n const insensitive =\n clause.mode === \"insensitive\" && typeof clause.value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n return insensitive\n ? not(column.ilike(escapeLike(clause.value)))\n : column.isNot(clause.value);\n case \"in\":\n return column.in(clause.value);\n case \"not_in\":\n return column.notIn(clause.value);\n case \"gt\":\n return column.above(clause.value);\n case \"gte\":\n return column.atLeast(clause.value);\n case \"lt\":\n return column.below(clause.value);\n case \"lte\":\n return column.atMost(clause.value);\n case \"contains\":\n return pattern(`%${escapeLike(clause.value)}%`);\n case \"starts_with\":\n return pattern(`${escapeLike(clause.value)}%`);\n case \"ends_with\":\n return pattern(`%${escapeLike(clause.value)}`);\n default:\n return insensitive\n ? column.ilike(escapeLike(clause.value))\n : column.is(clause.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 CleanedWhere[] | 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\nconst snakeCase = (name: string): string =>\n name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\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({ ... })`.\n */\nexport const authSchemaSource = (tables: Tables): string => {\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 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 targets = Object.values(entry.fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(entry.fields).map(([key, field]) => {\n const named =\n field.fieldName &&\n field.fieldName !== key &&\n field.fieldName !== snakeCase(key)\n ? `.named(${JSON.stringify(field.fieldName)})`\n : \"\";\n const reference = field.references;\n\n if (reference && reference.field === \"id\" && key.endsWith(\"Id\")) {\n const target = nameOf(reference.model);\n // better-auth's own migrations cascade when a reference names no action.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\"\n ? \"setNull\"\n : undefined;\n const relation = key.slice(0, -2);\n const self = target === entry.modelName;\n\n // Two keys to one table need names for their reverse sides.\n if (targets.filter((name) => name === target).length > 1 || self) {\n if (self) {\n builders.add(\"self\");\n }\n\n return ` ${relation}: ${self ? \"self\" : target}${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)}`)}),`;\n }\n\n const claim =\n field.required === false || action === \"setNull\" ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${target})${action ? `.${action}` : \"\"}${field.unique ? \".unique\" : \"\"},`;\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\n return ` ${key}: ${type}${named}${field.required === false ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \"\"}${field.index && !field.unique ? \".index\" : \"\"}${literal},`;\n });\n const indexes = (entry.indexes ?? []).filter(\n (definition) => definition.fields.length > 1,\n );\n\n if (indexes.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${entry.modelName} = table({`,\n \" id: text,\",\n ...lines,\n indexes.length\n ? `}).indexes((${entry.modelName}) => ({\\n${indexes\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).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.map((entry) => entry.modelName).join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\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\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 transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: () => {\n const table = (model: string) => {\n const handle = 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 // 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 mutation: Loose,\n where: readonly CleanedWhere[] | undefined,\n ) => (where?.length ? mutation.where(filter(where)) : mutation.all());\n\n return {\n create: ({ model, data }) => table(model).insert(data).returning(),\n\n findOne: ({ model, where }) =>\n table(model)({ where: filter(where), limit: 1 }).first(),\n\n findMany: ({ model, where, limit, offset, sortBy }) =>\n table(model)({\n where: filter(where),\n limit,\n offset,\n orderBy: sortBy\n ? { [sortBy.field]: sortBy.direction }\n : undefined,\n }),\n\n count: ({ model, where }) =>\n table(model)({ where: filter(where) }).count(),\n\n update: async ({ model, where, update }) => {\n const [row] = await filtered(\n table(model).update(update),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n updateMany: async ({ model, where, update }) =>\n (await filtered(table(model).update(update), where)).affectedRows,\n\n delete: async ({ model, where }) => {\n await filtered(table(model).delete(), where);\n },\n\n deleteMany: async ({ model, where }) =>\n (await filtered(table(model).delete(), where)).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 }) => {\n const found = await table(model)({\n where: filter(where),\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 row ?? null;\n },\n\n incrementOne: async ({ model, where, increment, set }) => {\n const [row] = await table(model)\n .update((current: Loose) => ({\n ...set,\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => [\n field,\n current[field].plus(delta),\n ]),\n ),\n }))\n .where(filter(where))\n .returning();\n\n return row ?? null;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables),\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;AAElE,MAAM,aAAa,KAAY,WAAyB;CACtD,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,iCAC1D;CAGF,MAAM,cACJ,OAAO,SAAS,iBAAiB,OAAO,OAAO,UAAU;CAC3D,MAAM,WAAW,SACf,cAAc,OAAO,MAAM,IAAI,IAAI,OAAO,KAAK,IAAI;CAErD,QAAQ,OAAO,UAAf;EACE,KAAK,MACH,OAAO,cACH,IAAI,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,IAC1C,OAAO,MAAM,OAAO,KAAK;EAC/B,KAAK,MACH,OAAO,OAAO,GAAG,OAAO,KAAK;EAC/B,KAAK,UACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,QAAQ,OAAO,KAAK;EACpC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,OAAO,OAAO,KAAK;EACnC,KAAK,YACH,OAAO,QAAQ,IAAI,WAAW,OAAO,KAAK,EAAE,EAAE;EAChD,KAAK,eACH,OAAO,QAAQ,GAAG,WAAW,OAAO,KAAK,EAAE,EAAE;EAC/C,KAAK,aACH,OAAO,QAAQ,IAAI,WAAW,OAAO,KAAK,GAAG;EAC/C,SACE,O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,iBAAiB,MAAgB;KACvC,MAAM,QAAQ;KACd,WAAW;IACb;GACF;EACF;CACF,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 { and, 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\nconst predicate = (row: Loose, clause: CleanedWhere) => {\n const column = row[clause.field];\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${clause.field}\", which the table does not have`,\n );\n }\n\n const insensitive =\n clause.mode === \"insensitive\" && typeof clause.value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n return insensitive\n ? not(column.ilike(escapeLike(clause.value)))\n : column.isNot(clause.value);\n case \"in\":\n return column.in(clause.value);\n case \"not_in\":\n return column.notIn(clause.value);\n case \"gt\":\n return column.above(clause.value);\n case \"gte\":\n return column.atLeast(clause.value);\n case \"lt\":\n return column.below(clause.value);\n case \"lte\":\n return column.atMost(clause.value);\n case \"contains\":\n return pattern(`%${escapeLike(clause.value)}%`);\n case \"starts_with\":\n return pattern(`${escapeLike(clause.value)}%`);\n case \"ends_with\":\n return pattern(`%${escapeLike(clause.value)}`);\n default:\n return insensitive\n ? column.ilike(escapeLike(clause.value))\n : column.is(clause.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 CleanedWhere[] | 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\nconst snakeCase = (name: string): string =>\n name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\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({ ... })`.\n */\nexport const authSchemaSource = (tables: Tables): string => {\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 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 targets = Object.values(entry.fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(entry.fields).map(([key, field]) => {\n const named =\n field.fieldName &&\n field.fieldName !== key &&\n field.fieldName !== snakeCase(key)\n ? `.named(${JSON.stringify(field.fieldName)})`\n : \"\";\n const reference = field.references;\n\n if (reference && reference.field === \"id\" && key.endsWith(\"Id\")) {\n const target = nameOf(reference.model);\n // better-auth's own migrations cascade when a reference names no action.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\"\n ? \"setNull\"\n : undefined;\n const relation = key.slice(0, -2);\n const self = target === entry.modelName;\n\n // Two keys to one table need names for their reverse sides.\n if (targets.filter((name) => name === target).length > 1 || self) {\n if (self) {\n builders.add(\"self\");\n }\n\n return ` ${relation}: ${self ? \"self\" : target}${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)}`)}),`;\n }\n\n const claim =\n field.required === false || action === \"setNull\" ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${target})${action ? `.${action}` : \"\"}${field.unique ? \".unique\" : \"\"},`;\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\n return ` ${key}: ${type}${named}${field.required === false ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \"\"}${field.index && !field.unique ? \".index\" : \"\"}${literal},`;\n });\n const indexes = (entry.indexes ?? []).filter(\n (definition) => definition.fields.length > 1,\n );\n\n if (indexes.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${entry.modelName} = table({`,\n \" id: text,\",\n ...lines,\n indexes.length\n ? `}).indexes((${entry.modelName}) => ({\\n${indexes\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).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.map((entry) => entry.modelName).join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\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\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 transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: () => {\n const table = (model: string) => {\n const handle = 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 // 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 mutation: Loose,\n where: readonly CleanedWhere[] | undefined,\n ) => (where?.length ? mutation.where(filter(where)) : mutation.all());\n\n return {\n create: ({ model, data }) => table(model).insert(data).returning(),\n\n findOne: ({ model, where }) =>\n table(model)({ where: filter(where), limit: 1 }).first(),\n\n findMany: ({ model, where, limit, offset, sortBy }) =>\n table(model)({\n where: filter(where),\n limit,\n offset,\n orderBy: sortBy\n ? { [sortBy.field]: sortBy.direction }\n : undefined,\n }),\n\n count: ({ model, where }) =>\n table(model)({ where: filter(where) }).count(),\n\n update: async ({ model, where, update }) => {\n const [row] = await filtered(\n table(model).update(update),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n updateMany: async ({ model, where, update }) =>\n (await filtered(table(model).update(update), where)).affectedRows,\n\n delete: async ({ model, where }) => {\n await filtered(table(model).delete(), where);\n },\n\n deleteMany: async ({ model, where }) =>\n (await filtered(table(model).delete(), where)).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 }) => {\n const found = await table(model)({\n where: filter(where),\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 row ?? null;\n },\n\n incrementOne: async ({ model, where, increment, set }) => {\n const [row] = await filtered(\n table(model).update((current: Loose) => ({\n ...set,\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => [\n field,\n current[field].plus(delta),\n ]),\n ),\n })),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables),\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;AAElE,MAAM,aAAa,KAAY,WAAyB;CACtD,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,iCAC1D;CAGF,MAAM,cACJ,OAAO,SAAS,iBAAiB,OAAO,OAAO,UAAU;CAC3D,MAAM,WAAW,SACf,cAAc,OAAO,MAAM,IAAI,IAAI,OAAO,KAAK,IAAI;CAErD,QAAQ,OAAO,UAAf;EACE,KAAK,MACH,OAAO,cACH,IAAI,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,IAC1C,OAAO,MAAM,OAAO,KAAK;EAC/B,KAAK,MACH,OAAO,OAAO,GAAG,OAAO,KAAK;EAC/B,KAAK,UACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,QAAQ,OAAO,KAAK;EACpC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,OAAO,OAAO,KAAK;EACnC,KAAK,YACH,OAAO,QAAQ,IAAI,WAAW,OAAO,KAAK,EAAE,EAAE;EAChD,KAAK,eACH,OAAO,QAAQ,GAAG,WAAW,OAAO,KAAK,EAAE,EAAE;EAC/C,KAAK,aACH,OA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AO,EAAE,QAAQ,YAAY;KACzC,MAAM,iBAAiB,MAAgB;KACvC,MAAM,QAAQ;KACd,WAAW;IACb;GACF;EACF;CACF,CAAC;CAEH,MAAM,UAAU,MAAM,EAAE;CAExB,QAAQ,sBAAyC;EAC/C,cAAc;EAEd,OAAO,QAAQ,iBAAiB;CAClC;AACF"}
package/dist/bun.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-C2s_w1LW.js";
2
- import { t as PostgresDriver } from "./pool-XG_sgock.js";
1
+ import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-r3vlr_gE.js";
2
+ import { t as PostgresDriver } from "./pool-DLmybA--.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.d.ts
5
5
  type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
package/dist/bun.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as SCHEMA_BIND } from "./binding-jM09pXvJ.js";
2
- import { n as postgresParameters, t as createPostgresDriver } from "./pool-C3RZQz3X.js";
2
+ import { n as postgresParameters, t as createPostgresDriver } from "./pool-dF8wVzv2.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.ts
5
5
  /**
package/dist/cohere.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-C2s_w1LW.js";
1
+ import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-r3vlr_gE.js";
2
2
  //#region src/entries/cohere.d.ts
3
3
  export type CohereOptions = {
4
4
  readonly apiKey?: string;
package/dist/cohere.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as embedder } from "./search-jZqgEILM.js";
1
+ import { r as embedder } from "./search-D953bVPb.js";
2
2
  import { i as postJson, r as inBatches, t as apiKey } from "./http-o1fpnTNy.js";
3
3
  //#region src/entries/cohere.ts
4
4
  /**
@@ -1,7 +1,7 @@
1
- import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-BCMCu-EF.js";
2
- import { $ as tsquerySql, G as createCompilation, J as renderContext, K as parameter, Q as sqlString, W as aliasSql, X as searchRankSql, Y as searchHeadlineSql, Z as searchVectorSql, et as tsvectorSql, q as quoteIdentifier } from "./table-BOy3SI0b.js";
1
+ import { a as containsBinding, c as numberedAlias, f as cloneParameter, g as createRowDecoder, o as mergeBindings, s as normalizeResult, t as DEFAULT_VALUE, u as bigintCodec, w as throwDataErrors, y as numericCodec } from "./types-NVB9dmsW.js";
2
+ import { $ as tsquerySql, G as createCompilation, J as renderContext, K as parameter, Q as sqlString, W as aliasSql, X as searchRankSql, Y as searchHeadlineSql, Z as searchVectorSql, et as tsvectorSql, q as quoteIdentifier } from "./table-x4L0cE1T.js";
3
3
  import { c as scopeViolationText } from "./binding-jM09pXvJ.js";
4
- import { I as freeze, M as expressionSqlType, N as childNodes, P as containsNode } from "./core-kaO0qvAO.js";
4
+ import { I as freeze, M as expressionSqlType, N as childNodes, P as containsNode } from "./core-j8XuMGmY.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { createServer } from "node:http";
@@ -447,7 +447,7 @@ const valueSql = (compilation, node, bindings, jsonOutput = false) => {
447
447
  const existing = cache?.find((entry) => sameExpression(entry.node, node) && (entry.jsonOutput === jsonOutput || !compilation.shapeOnly && !containsNode(node, buildsJson)));
448
448
  if (existing) return existing.sql;
449
449
  const sql = renderValue(compilation, node, bindings, jsonOutput);
450
- if (!BARE_PARAMETER.test(sql)) cache?.push({
450
+ if (cache && !BARE_PARAMETER.test(sql)) cache.push({
451
451
  node,
452
452
  sql,
453
453
  jsonOutput
@@ -1091,6 +1091,18 @@ const ordersThroughIvfflat = (query) => {
1091
1091
  const column = node?.kind === "binary" && node.left.kind === "column" ? node.left.description : void 0;
1092
1092
  return !!column && !query.locking && !query.distinct && !query.grouping.length && (column.binding.table.indexes ?? []).some((definition) => definition.method === "ivfflat" && definition.keys[0]?.startsWith(quoteIdentifier(column.column.sqlName)));
1093
1093
  };
1094
+ const carriedLists = /* @__PURE__ */ new WeakMap();
1095
+ /** Every column of the root under its own name, for a page taken before its nested rows. */
1096
+ const carriedColumns = (root, alias) => {
1097
+ let lists = carriedLists.get(root.table);
1098
+ if (!lists) carriedLists.set(root.table, lists = /* @__PURE__ */ new Map());
1099
+ let list = lists.get(alias);
1100
+ if (list === void 0) {
1101
+ list = root.table.columns.map((column) => `${alias}.${quoteIdentifier(column.sqlName)} AS ${quoteIdentifier(column.sqlName)}`).join(", ");
1102
+ if (lists.size < 64) lists.set(alias, list);
1103
+ }
1104
+ return list;
1105
+ };
1094
1106
  const NO_SHARED_AGGREGATES = {
1095
1107
  inner: [],
1096
1108
  outer: []
@@ -1150,9 +1162,11 @@ const renderSelect = (compilation, query, outerBindings, jsonValues, jsonOutput)
1150
1162
  const count = (value) => value === void 0 ? void 0 : typeof value === "number" ? String(value) : valueSql(compilation, value, bindings);
1151
1163
  fragments.push(...compilation.renderer.limitOffset(count(query.limit), count(query.offset)));
1152
1164
  if (query.locking) {
1165
+ const outer = query.joins.some((join) => join.kind === "LEFT");
1166
+ const reachable = !query.locking.of && outer && query.joins.every((join) => join.kind !== "RIGHT" && join.kind !== "FULL") ? [query.root, ...query.joins.filter((join) => join.kind !== "LEFT" && !join.binding.cte && !join.binding.cteReference).map((join) => join.binding)].map((binding) => aliasSql(compilation, binding)) : void 0;
1153
1167
  const lock = compilation.renderer.rowLock({
1154
1168
  mode: query.locking.mode,
1155
- of: query.locking.of?.map((alias) => aliasSql(compilation, query.bindings[alias])),
1169
+ of: reachable ?? query.locking.of?.map((alias) => aliasSql(compilation, query.bindings[alias])),
1156
1170
  noWait: !!query.locking.noWait,
1157
1171
  skipLocked: !!query.locking.skipLocked
1158
1172
  });
@@ -1180,7 +1194,7 @@ const renderSelect = (compilation, query, outerBindings, jsonValues, jsonOutput)
1180
1194
  return [
1181
1195
  projection,
1182
1196
  `FROM (${[
1183
- `SELECT ${query.root.table.columns.map((column) => `${aliasSql(compilation, query.root)}.${quoteIdentifier(column.sqlName)} AS ${quoteIdentifier(column.sqlName)}`).join(", ")}`,
1197
+ `SELECT ${carriedColumns(query.root, aliasSql(compilation, query.root))}`,
1184
1198
  source,
1185
1199
  ...body,
1186
1200
  ...fragments
@@ -1302,7 +1316,7 @@ const mutationSql = (compilation, query) => {
1302
1316
  }
1303
1317
  }
1304
1318
  } else {
1305
- if (!query.predicates.length && !query.unrestricted) throw new Error(`symmetria: ${query.kind}() on "${query.root.table.name}" has no where(); call .all() to ${query.kind === "update" ? "update" : "delete"} every row`);
1319
+ if (!query.predicates.some((predicate) => predicate.kind !== "scope") && !query.unrestricted) throw new Error(`symmetria: ${query.kind}() on "${query.root.table.name}" has no where(); call .all() to ${query.kind === "update" ? "update" : "delete"} every row`);
1306
1320
  fragments.push(query.kind === "update" ? `UPDATE ${tableSql(compilation, query.root)} SET ${assignments(query.values[0])}` : `DELETE FROM ${tableSql(compilation, query.root)}`);
1307
1321
  }
1308
1322
  if (query.predicates.length) fragments.push(`WHERE ${query.predicates.map((description) => predicateSql(compilation, description, query.bindings)).join(" AND ")}`);
@@ -1592,4 +1606,4 @@ const rowDecoder = (plan) => {
1592
1606
  //#endregion
1593
1607
  export { currentScopes as a, rowDecoder as c, createProfiler as d, executorProfiling as f, compileTemplate as i, queryOccurrence as l, compileQuery as n, executeCompiled as o, postgresRenderer as p, compileShape as r, executePlan as s, compilePlan as t, batchCollectors as u };
1594
1608
 
1595
- //# sourceMappingURL=compile-hFOq0snq.js.map
1609
+ //# sourceMappingURL=compile-Cfv7061C.js.map