@prisma/orm-better-auth 8.0.0-rc.25-dev.8 → 8.0.0-rc.25-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,79 +1,10 @@
1
+ import { _ as assertFieldName, c as describeFieldType, d as caseOnlyNameCollisions, f as ambiguousModelMessage, h as missingModelMessage, l as codecKind, n as createContractCheck, p as findModel, r as registerContractCheck, s as compareContract, t as contractMismatchError, u as betterAuthModels, v as assertModelName, y as caseOnlyNameCollisionMessage } from "./contract-check-Cw4rCQvX.mjs";
1
2
  import { getAuthTables } from "@better-auth/core/db";
2
3
  import { createAdapterFactory } from "@better-auth/core/db/adapter";
3
4
  import { BetterAuthError } from "@better-auth/core/error";
4
5
  import { blindCast } from "@prisma/orm-framework/utils/casts";
5
6
  import { UNBOUND_DOMAIN_NAMESPACE_ID } from "@prisma/orm-framework/contract/default-namespace";
6
- import * as internal from "@better-auth/core/db/internal";
7
- import { resolveStorageTable } from "@prisma/orm-family-sql/contract/resolve-storage-table";
8
7
  import { all, and, or } from "@prisma/orm-family-sql/orm-client";
9
- //#region src/models/identifiers.ts
10
- const pslIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
11
- function isPslIdentifier(name) {
12
- return pslIdentifier.test(name);
13
- }
14
- /** The message for a Better Auth model name that is not a Prisma identifier, or `undefined` when it is one. */
15
- function invalidModelNameMessage(name) {
16
- if (isPslIdentifier(name)) return void 0;
17
- return `Better Auth's model name "${name}" is not a valid Prisma model name: use letters, digits and "_", not starting with a digit. Rename the model with Better Auth's "modelName" option.`;
18
- }
19
- /** The message for a Better Auth field name that is not a Prisma identifier, or `undefined` when it is one. */
20
- function invalidFieldNameMessage(model, field) {
21
- if (isPslIdentifier(field)) return void 0;
22
- return `Better Auth's field name "${field}" of model "${model}" is not a valid Prisma field name: use letters, digits and "_", not starting with a digit. Rename the field with Better Auth's "fields" option.`;
23
- }
24
- /** The message for Better Auth models whose names differ only in the case of the first letter. */
25
- function caseOnlyNameCollisionMessage(names) {
26
- const quoted = names.map((name) => `"${name}"`);
27
- return `Better Auth's models ${`${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`} have names that differ only in the case of the first letter, which this adapter does not support. Set a different "modelName" on all but one of them in your Better Auth configuration.`;
28
- }
29
- function assertModelName(name) {
30
- const message = invalidModelNameMessage(name);
31
- if (message !== void 0) throw new BetterAuthError(message);
32
- }
33
- function assertFieldName(model, field) {
34
- const message = invalidFieldNameMessage(model, field);
35
- if (message !== void 0) throw new BetterAuthError(message);
36
- }
37
- function upperFirst(name) {
38
- return name.charAt(0).toUpperCase() + name.slice(1);
39
- }
40
- function lowerFirst(name) {
41
- return name.charAt(0).toLowerCase() + name.slice(1);
42
- }
43
- //#endregion
44
- //#region src/models/model-lookup.ts
45
- function missingModelMessage(physicalName) {
46
- return `Model "${physicalName}" is not in your Prisma contract. Run \`npx auth@latest generate\` to see what to add.`;
47
- }
48
- function ambiguousModelMessage(name, namespaceIds) {
49
- return `Model "${name}" is in more than one namespace of your Prisma contract (${namespaceIds.join(", ")}). Set the adapter's "namespace" option.`;
50
- }
51
- /**
52
- * Finds the contract model for a Better Auth physical model name: the exact name first, then the name with its first letter upper-cased, in the namespace the adapter's `namespace` option names or else in every namespace. The physical model name is matched to a contract model name, never to a table name.
53
- */
54
- function findModel(contract, physicalName, namespace) {
55
- const namespaces = contract.domain.namespaces;
56
- const searched = namespace === void 0 ? Object.keys(namespaces) : [namespace].filter((id) => Object.hasOwn(namespaces, id));
57
- const candidates = [.../* @__PURE__ */ new Set([physicalName, upperFirst(physicalName)])];
58
- for (const name of candidates) {
59
- const hits = searched.filter((id) => Object.hasOwn(namespaces[id]?.models ?? {}, name)).sort();
60
- const [only] = hits;
61
- if (hits.length > 1) return {
62
- kind: "ambiguous",
63
- name,
64
- namespaceIds: hits
65
- };
66
- const model = only === void 0 ? void 0 : namespaces[only]?.models[name];
67
- if (only !== void 0 && model !== void 0) return {
68
- kind: "found",
69
- name,
70
- namespaceId: only,
71
- model
72
- };
73
- }
74
- return { kind: "missing" };
75
- }
76
- //#endregion
77
8
  //#region src/orm.ts
78
9
  const collectionMethods = [
79
10
  "where",
@@ -136,707 +67,6 @@ function createModelCollections(contract, namespace) {
136
67
  };
137
68
  }
138
69
  //#endregion
139
- //#region src/models/better-auth-models.ts
140
- function physicalName(modelName, usePlural) {
141
- return usePlural ? `${modelName}s` : modelName;
142
- }
143
- function isOmitted(key, table, options) {
144
- if (table.disableMigrations === true) return true;
145
- return key === "session" && options.secondaryStorage !== void 0 && options.session?.storeSessionInDatabase !== true;
146
- }
147
- function referencedTable(tables, model) {
148
- return tables[model] ?? Object.values(tables).find((table) => table.modelName === model);
149
- }
150
- function resolveReference(tables, references, usePlural) {
151
- const table = referencedTable(tables, references.model);
152
- const field = table?.fields[references.field];
153
- return {
154
- model: physicalName(table?.modelName ?? references.model, usePlural),
155
- field: field?.fieldName || references.field,
156
- onDelete: references.onDelete ?? "cascade"
157
- };
158
- }
159
- /**
160
- * The models Better Auth's table description names, one per physical model name, in Better Auth's table order. The adapter serves calls for all of them.
161
- */
162
- function betterAuthModels(tables, { betterAuthOptions, usePlural }) {
163
- const merged = /* @__PURE__ */ new Map();
164
- for (const [key, table] of Object.entries(tables)) {
165
- const name = physicalName(table.modelName, usePlural);
166
- const model = merged.get(name) ?? {
167
- fields: /* @__PURE__ */ new Map(),
168
- indexes: [],
169
- managed: false
170
- };
171
- model.managed ||= !isOmitted(key, table, betterAuthOptions);
172
- merged.set(name, model);
173
- for (const [fieldKey, attribute] of Object.entries(table.fields)) {
174
- const fieldName = attribute.fieldName || fieldKey;
175
- if (fieldName === "id") continue;
176
- model.fields.set(fieldName, {
177
- name: fieldName,
178
- attribute,
179
- reference: attribute.references === void 0 ? void 0 : resolveReference(tables, attribute.references, usePlural)
180
- });
181
- }
182
- for (const index of table.indexes ?? []) model.indexes.push({
183
- fields: index.fields.map((field) => table.fields[field]?.fieldName || field),
184
- unique: index.unique === true
185
- });
186
- }
187
- return [...merged].map(([name, { fields, indexes, managed }]) => ({
188
- physicalName: name,
189
- fields: [...fields.values()],
190
- indexes,
191
- managed
192
- }));
193
- }
194
- /** Groups of physical model names that differ only in the case of the first letter, which the adapter refuses. */
195
- function caseOnlyNameCollisions(models) {
196
- const byModelName = /* @__PURE__ */ new Map();
197
- for (const { physicalName } of models) {
198
- const name = upperFirst(physicalName);
199
- byModelName.set(name, [...byModelName.get(name) ?? [], physicalName]);
200
- }
201
- return [...byModelName.values()].filter((names) => names.length > 1);
202
- }
203
- /** The models of the schema Better Auth manages, which the comparison checks. */
204
- function managedModels(tables, options) {
205
- return betterAuthModels(tables, options).filter((model) => model.managed);
206
- }
207
- function idStrategyOf(options) {
208
- const generateId = options.advanced?.database?.generateId;
209
- if (generateId === "serial") return "serial";
210
- if (generateId === "uuid") return "uuid";
211
- if (generateId === false) return "contract";
212
- return "string";
213
- }
214
- /** Better Auth can write `null` to any optional field: its default value replaces only a missing value on create, never an explicit `null`. So the contract must declare the field optional. */
215
- function mayBeNull(attribute) {
216
- return attribute.required === false;
217
- }
218
- function isIdReference(attribute) {
219
- return attribute.references?.field === "id";
220
- }
221
- //#endregion
222
- //#region src/models/codec-kinds.ts
223
- const codecKinds = [
224
- "string",
225
- "enum",
226
- "uuid",
227
- "date",
228
- "number",
229
- "boolean",
230
- "other"
231
- ];
232
- const codecIdsByKind = {
233
- string: [
234
- "pg/text@1",
235
- "sql/varchar@1",
236
- "sql/char@1",
237
- "sqlite/text@1"
238
- ],
239
- enum: ["pg/enum@1"],
240
- uuid: ["pg/uuid@1"],
241
- date: [
242
- "pg/timestamptz-date@1",
243
- "pg/timestamp-date@1",
244
- "sqlite/datetime@1"
245
- ],
246
- number: [
247
- "pg/int2@1",
248
- "pg/int4@1",
249
- "pg/int8number@1",
250
- "pg/float4@1",
251
- "pg/float8@1",
252
- "sqlite/integer@1",
253
- "sqlite/real@1"
254
- ],
255
- boolean: ["pg/bool@1", "sqlite/boolean@1"],
256
- other: [
257
- "pg/int8@1",
258
- "pg/unboundedint@1",
259
- "pg/numeric@1",
260
- "pg/timestamptz-temporal@1",
261
- "pg/timestamptz-string@1",
262
- "pg/timestamp-temporal@1",
263
- "pg/timestamp-string@1",
264
- "pg/timestamp-instant@1",
265
- "pg/date-temporal@1",
266
- "pg/date-string@1",
267
- "pg/time-temporal@1",
268
- "pg/time-string@1",
269
- "pg/timetz@1",
270
- "pg/inet@1",
271
- "pg/interval@1",
272
- "pg/interval-string@1",
273
- "pg/bit@1",
274
- "pg/varbit@1",
275
- "pg/xml@1",
276
- "pg/oid@1",
277
- "pg/money@1",
278
- "pg/json@1",
279
- "pg/jsonb@1",
280
- "pg/bytea@1",
281
- "sqlite/bigint@1",
282
- "sqlite/decimal@1",
283
- "sqlite/datetime-temporal@1",
284
- "sqlite/datetime-string@1",
285
- "sqlite/date-string@1",
286
- "sqlite/date-temporal@1",
287
- "sqlite/time-string@1",
288
- "sqlite/time-temporal@1",
289
- "sqlite/duration-string@1",
290
- "sqlite/json@1",
291
- "sqlite/blob@1"
292
- ]
293
- };
294
- const kindByCodecId = new Map(codecKinds.flatMap((kind) => codecIdsByKind[kind].map((id) => [id, kind])));
295
- /** The kind of JavaScript value a codec reads and writes, or `undefined` for a codec this table does not know. */
296
- function codecKind(codecId) {
297
- return kindByCodecId.get(codecId);
298
- }
299
- //#endregion
300
- //#region src/models/field-type.ts
301
- /** What a contract field holds, as messages name it: its codec id, `<codec id> list`, `a value object` or `a union`. */
302
- function describeFieldType(field) {
303
- if (field.type.kind === "valueObject") return "a value object";
304
- if (field.type.kind === "union") return "a union";
305
- return field.many ? `${field.type.codecId} list` : field.type.codecId;
306
- }
307
- //#endregion
308
- //#region src/contract/compare.ts
309
- const acceptedKindsByIdStrategy = {
310
- serial: ["number"],
311
- uuid: ["string", "uuid"],
312
- string: ["string"],
313
- contract: ["string"]
314
- };
315
- const defaultNamespaceByTarget = { postgres: "public" };
316
- function acceptedKinds(attribute, idStrategy) {
317
- if (isIdReference(attribute)) return acceptedKindsByIdStrategy[idStrategy];
318
- switch (attribute.type) {
319
- case "number": return ["number"];
320
- case "boolean": return ["boolean"];
321
- case "date": return ["date"];
322
- case "string": return ["string", "enum"];
323
- default: return Array.isArray(attribute.type) ? ["string", "enum"] : ["string"];
324
- }
325
- }
326
- /** The description of a contract field whose type Better Auth cannot use, or `undefined` when it can. */
327
- function wrongTypeFound(field, accepted) {
328
- if (field.type.kind !== "scalar" || field.many) return describeFieldType(field);
329
- const kind = codecKind(field.type.codecId);
330
- return kind === void 0 || accepted.includes(kind) ? void 0 : describeFieldType(field);
331
- }
332
- function isSqlModelStorage(storage) {
333
- return typeof storage["table"] === "string" && typeof storage["namespaceId"] === "string";
334
- }
335
- function columnFacts(contract, found, field) {
336
- const storage = found.model.storage;
337
- if (!isSqlModelStorage(storage)) return {
338
- hasDatabaseDefault: false,
339
- hasCreateGenerator: false
340
- };
341
- const column = storage.fields[field]?.column ?? field;
342
- return {
343
- hasDatabaseDefault: (resolveStorageTable(contract.storage, storage.table, storage.namespaceId)?.table)?.columns[column]?.default !== void 0,
344
- hasCreateGenerator: (contract.execution?.mutations.defaults ?? []).some(({ ref, onCreate }) => onCreate !== void 0 && ref.namespace === storage.namespaceId && ref.entry === storage.table && ref.field === column)
345
- };
346
- }
347
- function compareFoundModel(contract, expected, found, idStrategy, problems) {
348
- const fields = found.model.fields;
349
- const model = found.name;
350
- const missingFields = [];
351
- const id = fields["id"];
352
- if (id === void 0) missingFields.push("id");
353
- else {
354
- const wrong = wrongTypeFound(id, acceptedKindsByIdStrategy[idStrategy]);
355
- if (wrong !== void 0) problems.push({
356
- kind: "wrong-type",
357
- model,
358
- field: "id",
359
- attribute: void 0,
360
- reference: void 0,
361
- found: wrong
362
- });
363
- const facts = columnFacts(contract, found, "id");
364
- if ((idStrategy === "serial" || idStrategy === "contract") && !facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
365
- kind: "id-without-default",
366
- model
367
- });
368
- }
369
- for (const field of expected.fields) {
370
- const contractField = fields[field.name];
371
- if (contractField === void 0) {
372
- missingFields.push(field.name);
373
- continue;
374
- }
375
- const wrong = wrongTypeFound(contractField, acceptedKinds(field.attribute, idStrategy));
376
- if (wrong !== void 0) problems.push({
377
- kind: "wrong-type",
378
- model,
379
- field: field.name,
380
- attribute: field.attribute,
381
- reference: field.reference,
382
- found: wrong
383
- });
384
- else if (mayBeNull(field.attribute) && !contractField.nullable) problems.push({
385
- kind: "optional-field-not-nullable",
386
- model,
387
- field: field.name,
388
- attribute: field.attribute,
389
- reference: field.reference
390
- });
391
- }
392
- for (const field of missingFields) problems.push({
393
- kind: "missing-field",
394
- model,
395
- field
396
- });
397
- const written = /* @__PURE__ */ new Set(["id", ...expected.fields.map((field) => field.name)]);
398
- for (const [name, field] of Object.entries(fields)) {
399
- if (written.has(name) || field.nullable) continue;
400
- const facts = columnFacts(contract, found, name);
401
- if (!facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
402
- kind: "required-field-not-written",
403
- model,
404
- field: name
405
- });
406
- }
407
- return missingFields;
408
- }
409
- function hasUuidId(found) {
410
- const id = found.model.fields["id"];
411
- return id?.type.kind === "scalar" && codecKind(id.type.codecId) === "uuid";
412
- }
413
- function uuidKeyedModelsOf(models, referencedModels) {
414
- const found = [...models.flatMap((model) => model.status === "found" ? [[model.expected.physicalName, model.found]] : []), ...referencedModels];
415
- return new Set(found.filter(([, model]) => hasUuidId(model)).map(([name]) => name));
416
- }
417
- /** A model or field name that is not a Prisma identifier can be neither matched nor printed, so it is the only problem reported. */
418
- function invalidNameProblems(models) {
419
- return models.flatMap((model) => [...isPslIdentifier(model.physicalName) ? [] : [{
420
- kind: "invalid-name",
421
- model: model.physicalName
422
- }], ...model.fields.filter((field) => !isPslIdentifier(field.name)).map((field) => ({
423
- kind: "invalid-name",
424
- model: model.physicalName,
425
- field: field.name
426
- }))]);
427
- }
428
- /**
429
- * Compares the contract with the models and fields Better Auth's table description asks for. The contract check and `auth generate` both use it.
430
- */
431
- function compareContract(input) {
432
- const { contract, betterAuthOptions, namespace } = input;
433
- const idStrategy = idStrategyOf(betterAuthOptions);
434
- const defaultNamespace = defaultNamespaceByTarget[contract.target] ?? UNBOUND_DOMAIN_NAMESPACE_ID;
435
- const expectedModelList = managedModels(input.tables, input);
436
- const nameProblems = [...invalidNameProblems(expectedModelList), ...caseOnlyNameCollisions(betterAuthModels(input.tables, input)).map((models) => ({
437
- kind: "colliding-model-names",
438
- models
439
- }))];
440
- if (nameProblems.length > 0) return {
441
- models: [],
442
- problems: nameProblems,
443
- referencedModels: /* @__PURE__ */ new Map(),
444
- uuidKeyedModels: /* @__PURE__ */ new Set(),
445
- idStrategy,
446
- namespace,
447
- defaultNamespace
448
- };
449
- const problems = [];
450
- const models = [];
451
- for (const expected of expectedModelList) {
452
- const lookup = findModel(contract, expected.physicalName, namespace);
453
- switch (lookup.kind) {
454
- case "missing":
455
- problems.push({
456
- kind: "missing-model",
457
- model: expected.physicalName
458
- });
459
- models.push({
460
- status: "missing",
461
- expected
462
- });
463
- break;
464
- case "ambiguous":
465
- problems.push({
466
- kind: "ambiguous-model",
467
- model: lookup.name,
468
- namespaceIds: lookup.namespaceIds
469
- });
470
- models.push({
471
- status: "ambiguous",
472
- expected
473
- });
474
- break;
475
- case "found": {
476
- const missingFields = compareFoundModel(contract, expected, lookup, idStrategy, problems);
477
- models.push({
478
- status: "found",
479
- expected,
480
- found: lookup,
481
- missingFields
482
- });
483
- break;
484
- }
485
- }
486
- }
487
- const expectedNames = new Set(expectedModelList.map((model) => model.physicalName));
488
- const referencedModels = /* @__PURE__ */ new Map();
489
- for (const model of expectedModelList) for (const { reference } of model.fields) {
490
- if (reference === void 0 || expectedNames.has(reference.model)) continue;
491
- const lookup = findModel(contract, reference.model, namespace);
492
- if (lookup.kind === "found") referencedModels.set(reference.model, lookup);
493
- }
494
- return {
495
- models,
496
- problems,
497
- referencedModels,
498
- uuidKeyedModels: acceptedKindsByIdStrategy[idStrategy].includes("uuid") ? uuidKeyedModelsOf(models, referencedModels) : /* @__PURE__ */ new Set(),
499
- idStrategy,
500
- namespace,
501
- defaultNamespace
502
- };
503
- }
504
- //#endregion
505
- //#region src/contract/psl-types.ts
506
- /** How a Better Auth field is written in PSL, without `?`. A foreign key to a model whose `id` is a `Uuid` is a `Uuid`, since PostgreSQL refuses a `text` key that references a `uuid`. */
507
- function pslTypeOf(attribute, reference, { idStrategy, uuidKeyedModels }) {
508
- if (isIdReference(attribute)) {
509
- if (reference !== void 0 && uuidKeyedModels.has(reference.model)) return "Uuid";
510
- return idStrategy === "serial" ? "Int" : "String";
511
- }
512
- switch (attribute.type) {
513
- case "number": return attribute.bigint === true ? "BigInt(as: number)" : "Int";
514
- case "boolean": return "Boolean";
515
- case "date": return "DateTime";
516
- default: return "String";
517
- }
518
- }
519
- /** The `id` field the printed PSL declares, as its columns. */
520
- function idFieldOf(idStrategy) {
521
- switch (idStrategy) {
522
- case "serial": return {
523
- name: "id",
524
- type: "Int",
525
- attributes: "@id @default(autoincrement())"
526
- };
527
- case "contract": return {
528
- name: "id",
529
- type: "String",
530
- attributes: "@id @onCreate(uuid())"
531
- };
532
- default: return {
533
- name: "id",
534
- type: "String",
535
- attributes: "@id"
536
- };
537
- }
538
- }
539
- function idLineOf(idStrategy) {
540
- const { name, type, attributes } = idFieldOf(idStrategy);
541
- return `${name} ${type} ${attributes}`;
542
- }
543
- //#endregion
544
- //#region src/contract/print-psl.ts
545
- const actionNames = {
546
- cascade: "Cascade",
547
- "no action": "NoAction",
548
- restrict: "Restrict",
549
- "set null": "SetNull",
550
- "set default": "SetDefault"
551
- };
552
- function existingPrintedModel(found, betterAuthFields) {
553
- return {
554
- name: found.name,
555
- namespaceId: found.namespaceId,
556
- existing: true,
557
- taken: /* @__PURE__ */ new Set([
558
- ...betterAuthFields,
559
- ...Object.keys(found.model.fields),
560
- ...Object.keys(found.model.relations)
561
- ]),
562
- fields: [],
563
- backRelations: [],
564
- attributes: []
565
- };
566
- }
567
- function printedModelFor(model, comparison) {
568
- const betterAuthFields = ["id", ...model.expected.fields.map((field) => field.name)];
569
- switch (model.status) {
570
- case "missing": return {
571
- name: upperFirst(model.expected.physicalName),
572
- namespaceId: comparison.namespace ?? comparison.defaultNamespace,
573
- existing: false,
574
- taken: new Set(betterAuthFields),
575
- fields: [],
576
- backRelations: [],
577
- attributes: []
578
- };
579
- case "found": return existingPrintedModel(model.found, betterAuthFields);
580
- case "ambiguous": return;
581
- }
582
- }
583
- function typeName(of, from) {
584
- return of.namespaceId === from.namespaceId ? of.name : `${of.namespaceId}.${of.name}`;
585
- }
586
- function scalarLine(field, comparison) {
587
- const optional = field.attribute.required === false ? "?" : "";
588
- const type = `${pslTypeOf(field.attribute, field.reference, comparison)}${optional}`;
589
- return field.attribute.unique === true ? [
590
- field.name,
591
- type,
592
- "@unique"
593
- ] : [field.name, type];
594
- }
595
- function idLine(comparison) {
596
- const { name, type, attributes } = idFieldOf(comparison.idStrategy);
597
- return [
598
- name,
599
- type,
600
- attributes
601
- ];
602
- }
603
- function freeName(name, printed) {
604
- let free = name;
605
- while (printed.taken.has(free)) free = `${free}_`;
606
- return free;
607
- }
608
- function relationFieldName(foreignKey, holder) {
609
- const stripped = foreignKey.endsWith("Id") ? foreignKey.slice(0, -2) : foreignKey;
610
- return stripped === "" || stripped === foreignKey || holder.taken.has(stripped) ? freeName(`${foreignKey}Relation`, holder) : stripped;
611
- }
612
- function foreignKeyCount(expected, referenced) {
613
- return expected.fields.filter((field) => field.reference?.model === referenced).length;
614
- }
615
- function indexLines(expected) {
616
- const lines = [...expected.fields.filter((field) => field.attribute.index === true && field.attribute.unique !== true).map((field) => `@@index([${field.name}])`), ...expected.indexes.map((index) => `${index.unique ? "@@unique" : "@@index"}([${index.fields.join(", ")}])`)];
617
- return [...new Set(lines)];
618
- }
619
- function alignedLines(lines) {
620
- const nameWidth = Math.max(0, ...lines.map(([name]) => name.length));
621
- const typeWidth = Math.max(0, ...lines.map(([, type]) => type.length));
622
- return lines.map(([name, type, attributes]) => attributes === void 0 || attributes === "" ? `${name.padEnd(nameWidth)} ${type}` : `${name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${attributes}`);
623
- }
624
- function blockText(block, indent) {
625
- const body = [...block.fieldLines.map((line) => ` ${line}`)];
626
- if (block.attributeLines.length > 0) body.push("", ...block.attributeLines.map((line) => ` ${line}`));
627
- return [
628
- `model ${block.modelName} {`,
629
- ...body,
630
- "}"
631
- ].map((line) => line === "" ? "" : `${indent}${line}`).join("\n");
632
- }
633
- /** PSL text for printed blocks; blocks of missing models go inside a `namespace` block when the adapter's `namespace` option is set. */
634
- function renderBlocks(blocks, namespace) {
635
- const chunks = [];
636
- let run = [];
637
- const flush = () => {
638
- if (run.length === 0) return;
639
- const inner = run.map((block) => blockText(block, " ")).join("\n\n");
640
- chunks.push(`namespace ${namespace} {\n${inner}\n}`);
641
- run = [];
642
- };
643
- for (const block of blocks) {
644
- if (namespace !== void 0 && !block.existing) {
645
- run.push(block);
646
- continue;
647
- }
648
- flush();
649
- chunks.push(blockText(block, ""));
650
- }
651
- flush();
652
- return chunks.join("\n\n");
653
- }
654
- /**
655
- * The PSL that adds what the comparison found missing: whole models for missing models, and the missing fields and new back-relation fields of existing models.
656
- */
657
- function printPsl(comparison) {
658
- const printedModels = /* @__PURE__ */ new Map();
659
- for (const model of comparison.models) {
660
- const printed = printedModelFor(model, comparison);
661
- if (printed !== void 0) printedModels.set(model.expected.physicalName, printed);
662
- }
663
- for (const [physicalName, found] of comparison.referencedModels) printedModels.set(physicalName, existingPrintedModel(found, []));
664
- const notes = [];
665
- for (const model of comparison.models) {
666
- const holder = printedModels.get(model.expected.physicalName);
667
- if (holder === void 0) continue;
668
- if (model.status === "found") {
669
- for (const name of model.missingFields) {
670
- const field = model.expected.fields.find((candidate) => candidate.name === name);
671
- holder.fields.push(field === void 0 ? idLine(comparison) : scalarLine(field, comparison));
672
- }
673
- continue;
674
- }
675
- holder.fields.push(idLine(comparison));
676
- for (const field of model.expected.fields) {
677
- holder.fields.push(scalarLine(field, comparison));
678
- const reference = field.reference;
679
- if (reference === void 0) continue;
680
- const referenced = printedModels.get(reference.model);
681
- const optional = field.attribute.required === false;
682
- let action = reference.onDelete;
683
- if (action === "set null" && !optional || action === "set default") {
684
- notes.push(`${holder.name}.${field.name}: Better Auth asks for onDelete ${action}, which needs ${action === "set null" ? "an optional field" : "a default"}; NoAction is printed instead`);
685
- action = "no action";
686
- }
687
- const relationName = relationFieldName(field.name, holder);
688
- holder.taken.add(relationName);
689
- let relationLabel;
690
- if (referenced !== void 0) {
691
- const list = field.attribute.unique !== true;
692
- const base = `${lowerFirst(holder.name)}${list ? "s" : ""}`;
693
- const named = referenced.taken.has(base) || foreignKeyCount(model.expected, reference.model) > 1;
694
- const backName = named ? freeName(`${base}By${upperFirst(field.name)}`, referenced) : base;
695
- relationLabel = named ? `"${holder.name}_${field.name}"` : void 0;
696
- referenced.taken.add(backName);
697
- referenced.backRelations.push([
698
- backName,
699
- `${typeName(holder, referenced)}${list ? "[]" : "?"}`,
700
- relationLabel === void 0 ? void 0 : `@relation(${relationLabel})`
701
- ]);
702
- }
703
- const referencedType = referenced === void 0 ? upperFirst(reference.model) : typeName(referenced, holder);
704
- const relationArguments = [
705
- ...relationLabel === void 0 ? [] : [relationLabel],
706
- `fields: [${field.name}]`,
707
- `references: [${reference.field}]`,
708
- `onDelete: ${actionNames[action]}`
709
- ].join(", ");
710
- holder.fields.push([
711
- relationName,
712
- `${referencedType}${optional ? "?" : ""}`,
713
- `@relation(${relationArguments})`
714
- ]);
715
- }
716
- holder.attributes.push(...indexLines(model.expected), `@@map("${model.expected.physicalName}")`);
717
- }
718
- const blocks = [];
719
- for (const printed of printedModels.values()) {
720
- const lines = [...printed.fields, ...printed.backRelations];
721
- if (lines.length === 0) continue;
722
- blocks.push({
723
- modelName: printed.name,
724
- existing: printed.existing,
725
- fieldLines: alignedLines(lines),
726
- attributeLines: printed.attributes
727
- });
728
- }
729
- return {
730
- blocks,
731
- notes,
732
- text: renderBlocks(blocks, comparison.namespace)
733
- };
734
- }
735
- //#endregion
736
- //#region src/contract/message.ts
737
- function section(title, lines) {
738
- return lines.length === 0 ? [] : [
739
- `${title}:`,
740
- "",
741
- ...lines.map((line) => ` ${line}`),
742
- ""
743
- ];
744
- }
745
- function changeLines(comparison) {
746
- const lines = [];
747
- const idLinesPrinted = /* @__PURE__ */ new Set();
748
- for (const problem of comparison.problems) switch (problem.kind) {
749
- case "ambiguous-model":
750
- lines.push(ambiguousModelMessage(problem.model, problem.namespaceIds));
751
- break;
752
- case "optional-field-not-nullable":
753
- lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}?\`, because Better Auth can write null to it`);
754
- break;
755
- case "id-without-default":
756
- case "wrong-type":
757
- if (problem.kind === "id-without-default" || problem.attribute === void 0) {
758
- if (idLinesPrinted.has(problem.model)) break;
759
- idLinesPrinted.add(problem.model);
760
- lines.push(`${problem.model}.id: must be \`${idLineOf(comparison.idStrategy)}\``);
761
- break;
762
- }
763
- lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}${mayBeNull(problem.attribute) ? "?" : ""}\` (found ${problem.found})`);
764
- break;
765
- }
766
- return lines;
767
- }
768
- function unwrittenLines(comparison) {
769
- return comparison.problems.flatMap((problem) => problem.kind === "required-field-not-written" ? [`${problem.model}.${problem.field}: make it optional or give it a default`] : []);
770
- }
771
- /**
772
- * The message the contract check and `auth generate` report, or `undefined` when the contract holds everything Better Auth needs.
773
- */
774
- function contractMessage(comparison) {
775
- if (comparison.problems.length === 0) return void 0;
776
- const invalidNames = comparison.problems.flatMap((problem) => {
777
- if (problem.kind === "colliding-model-names") return [caseOnlyNameCollisionMessage(problem.models)];
778
- if (problem.kind !== "invalid-name") return [];
779
- const message = problem.field === void 0 ? invalidModelNameMessage(problem.model) : invalidFieldNameMessage(problem.model, problem.field);
780
- return message === void 0 ? [] : [message];
781
- });
782
- if (invalidNames.length > 0) return invalidNames.join("\n");
783
- const psl = printPsl(comparison);
784
- const additions = psl.text === "" ? [] : [
785
- "Add to your contract:",
786
- "",
787
- psl.text,
788
- ""
789
- ];
790
- return [
791
- additions.length > 0 ? "Your Prisma contract is missing models or fields that Better Auth needs." : "Your Prisma contract does not match what Better Auth needs.",
792
- "",
793
- ...additions,
794
- ...section("Change in your contract", changeLines(comparison)),
795
- ...section("Fields Better Auth does not write", unwrittenLines(comparison)),
796
- ...section("Notes", psl.notes),
797
- "Then run `prisma contract emit` and update your database."
798
- ].join("\n");
799
- }
800
- //#endregion
801
- //#region src/contract/contract-check.ts
802
- /** The error the contract check rejects with and `createSchema` throws. Its `code` is what Better Auth's CLI looks for. */
803
- function contractMismatchError(message) {
804
- return Object.assign(new BetterAuthError(message), { code: "SCHEMA_MISMATCH" });
805
- }
806
- /** The mismatch error for a contract, or `undefined` when it holds everything Better Auth needs. */
807
- function contractMismatch(input) {
808
- const message = contractMessage(compareContract(input));
809
- return message === void 0 ? void 0 : contractMismatchError(message);
810
- }
811
- /**
812
- * A check that compares the contract on its first call and keeps the result: `undefined` when the contract is complete, and a promise rejected with the same error on every call when it is not.
813
- */
814
- function createContractCheck(input) {
815
- let verdict;
816
- return () => {
817
- if (verdict === void 0) try {
818
- const error = contractMismatch(input());
819
- verdict = error === void 0 ? { clean: true } : {
820
- clean: false,
821
- error
822
- };
823
- } catch (error) {
824
- verdict = {
825
- clean: false,
826
- error
827
- };
828
- }
829
- return verdict.clean ? void 0 : Promise.reject(verdict.error);
830
- };
831
- }
832
- /**
833
- * Registers the check with Better Auth, which runs it before requests, server-side API calls and transactions, and for `auth check`. Better Auth labels the entrypoint internal, so a version without `registerSchemaCheck` runs the adapter without a check.
834
- */
835
- function registerContractCheck(adapter, check, betterAuthOptions) {
836
- if (typeof internal.registerSchemaCheck !== "function") return;
837
- internal.registerSchemaCheck(adapter, check, { runtimeEnabled: betterAuthOptions.advanced?.database?.validateSchema !== false });
838
- }
839
- //#endregion
840
70
  //#region src/filters.ts
841
71
  /** The codec id a raw expression over the field returns. A field that is not a single scalar, or whose codec is known not to hold text, supports no pattern or case-insensitive comparison; a codec the table does not know is tried. */
842
72
  function scalarCodecIdOf(model, field, operator) {
@@ -1110,18 +340,19 @@ function customAdapter({ orm, contract, instance, adapterOptions }) {
1110
340
  return collection.where(filterFor(model, found, where)).deleteAndCount();
1111
341
  },
1112
342
  async createSchema({ file, tables }) {
1113
- const error = contractMismatch({
343
+ const comparison = compareContract({
1114
344
  contract,
1115
345
  tables,
1116
346
  betterAuthOptions,
1117
347
  namespace: adapterOptions.namespace,
1118
348
  usePlural
1119
349
  });
1120
- if (error !== void 0) throw error;
1121
- return {
350
+ if (comparison.problems.length === 0) return {
1122
351
  code: "",
1123
352
  path: file ?? "prisma/contract.prisma"
1124
353
  };
354
+ const { editedContractSource } = await import("./edited-contract-source-uFJmCt41.mjs");
355
+ return editedContractSource(file, comparison);
1125
356
  }
1126
357
  });
1127
358
  };