@zenstackhq/better-auth 3.5.6 → 3.6.1

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.d.ts DELETED
@@ -1,34 +0,0 @@
1
- import { BetterAuthOptions } from '@better-auth/core';
2
- import { DBAdapterDebugLogOption, DBAdapter } from '@better-auth/core/db/adapter';
3
- import { ClientContract } from '@zenstackhq/orm';
4
- import { SchemaDef } from '@zenstackhq/orm/schema';
5
-
6
- /**
7
- * Options for the ZenStack adapter factory.
8
- */
9
- interface AdapterConfig {
10
- /**
11
- * Database provider
12
- */
13
- provider: 'sqlite' | 'postgresql';
14
- /**
15
- * Enable debug logs for the adapter
16
- *
17
- * @default false
18
- */
19
- debugLogs?: DBAdapterDebugLogOption | undefined;
20
- /**
21
- * Use plural table names
22
- *
23
- * @default false
24
- */
25
- usePlural?: boolean | undefined;
26
- }
27
- /**
28
- * Create a Better-Auth adapter for ZenStack ORM.
29
- * @param db ZenStack ORM client instance
30
- * @param config adapter configuration options
31
- */
32
- declare const zenstackAdapter: <Schema extends SchemaDef>(db: ClientContract<Schema>, config: AdapterConfig) => (options: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;
33
-
34
- export { type AdapterConfig, zenstackAdapter };
package/dist/index.js DELETED
@@ -1,686 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/adapter.ts
5
- import { BetterAuthError } from "@better-auth/core/error";
6
- import { createAdapterFactory } from "better-auth/adapters";
7
-
8
- // src/schema-generator.ts
9
- import { lowerCaseFirst, upperCaseFirst } from "@zenstackhq/common-helpers";
10
- import { formatDocument, loadDocument, ZModelCodeGenerator } from "@zenstackhq/language";
11
- import { isDataModel } from "@zenstackhq/language/ast";
12
- import { hasAttribute } from "@zenstackhq/language/utils";
13
- import fs from "fs";
14
- import { match } from "ts-pattern";
15
- async function generateSchema(file, tables, config, options) {
16
- let filePath = file;
17
- if (!filePath) {
18
- if (fs.existsSync("./schema.zmodel")) {
19
- filePath = "./schema.zmodel";
20
- } else {
21
- filePath = "./zenstack/schema.zmodel";
22
- }
23
- }
24
- const schemaExists = fs.existsSync(filePath);
25
- const schema = await updateSchema(filePath, tables, config, options);
26
- return {
27
- code: schema ?? "",
28
- path: filePath,
29
- overwrite: schemaExists && !!schema
30
- };
31
- }
32
- __name(generateSchema, "generateSchema");
33
- async function updateSchema(schemaPath, tables, config, options) {
34
- let zmodel;
35
- if (fs.existsSync(schemaPath)) {
36
- const loadResult = await loadDocument(schemaPath);
37
- if (!loadResult.success) {
38
- throw new Error(`Failed to load existing schema at ${schemaPath}: ${loadResult.errors.join(", ")}`);
39
- }
40
- zmodel = loadResult.model;
41
- } else {
42
- zmodel = initializeZmodel(config);
43
- }
44
- const toManyRelations = /* @__PURE__ */ new Map();
45
- for (const [tableName, table] of Object.entries(tables)) {
46
- const fields = tables[tableName]?.fields;
47
- for (const field in fields) {
48
- const attr = fields[field];
49
- if (attr.references) {
50
- const referencedOriginalModel = attr.references.model;
51
- const referencedCustomModel = tables[referencedOriginalModel]?.modelName || referencedOriginalModel;
52
- const referencedModelNameCap = upperCaseFirst(referencedCustomModel);
53
- if (!toManyRelations.has(referencedModelNameCap)) {
54
- toManyRelations.set(referencedModelNameCap, /* @__PURE__ */ new Set());
55
- }
56
- const currentCustomModel = table.modelName ?? tableName;
57
- const currentModelNameCap = upperCaseFirst(currentCustomModel);
58
- toManyRelations.get(referencedModelNameCap).add(currentModelNameCap);
59
- }
60
- }
61
- }
62
- let changed = false;
63
- for (const [name, table] of Object.entries(tables)) {
64
- const c = addOrUpdateModel(name, table, zmodel, tables, toManyRelations, !!options.advanced?.database?.useNumberId);
65
- changed = changed || c;
66
- }
67
- if (!changed) {
68
- return void 0;
69
- }
70
- const generator = new ZModelCodeGenerator();
71
- let content = generator.generate(zmodel);
72
- try {
73
- content = await formatDocument(content);
74
- } catch {
75
- }
76
- return content;
77
- }
78
- __name(updateSchema, "updateSchema");
79
- function addDefaultNow(df) {
80
- const nowArg = {
81
- $type: "AttributeArg"
82
- };
83
- const nowExpr = {
84
- $type: "InvocationExpr",
85
- function: {
86
- $refText: "now"
87
- },
88
- args: [],
89
- $container: nowArg
90
- };
91
- nowArg.value = nowExpr;
92
- addFieldAttribute(df, "@default", [
93
- nowArg
94
- ]);
95
- }
96
- __name(addDefaultNow, "addDefaultNow");
97
- function createDataModel(modelName, zmodel, numericId) {
98
- const dataModel = {
99
- $type: "DataModel",
100
- name: modelName,
101
- fields: [],
102
- attributes: [],
103
- mixins: [],
104
- comments: [],
105
- isView: false,
106
- $container: zmodel
107
- };
108
- let idField;
109
- if (numericId) {
110
- idField = addModelField(dataModel, "id", "Int", false, false);
111
- } else {
112
- idField = addModelField(dataModel, "id", "String", false, false);
113
- }
114
- addFieldAttribute(idField, "@id");
115
- return dataModel;
116
- }
117
- __name(createDataModel, "createDataModel");
118
- function addModelField(dataModel, fieldName, fieldType, array, optional) {
119
- const field = {
120
- $type: "DataField",
121
- name: fieldName,
122
- attributes: [],
123
- comments: [],
124
- $container: dataModel
125
- };
126
- field.type = {
127
- $type: "DataFieldType",
128
- type: fieldType,
129
- array,
130
- optional,
131
- $container: field
132
- };
133
- dataModel.fields.push(field);
134
- return field;
135
- }
136
- __name(addModelField, "addModelField");
137
- function initializeZmodel(config) {
138
- const zmodel = {
139
- $type: "Model",
140
- declarations: [],
141
- imports: []
142
- };
143
- const ds = {
144
- $type: "DataSource",
145
- name: "db",
146
- fields: [],
147
- $container: zmodel
148
- };
149
- zmodel.declarations.push(ds);
150
- const providerField = {
151
- $type: "ConfigField",
152
- name: "provider",
153
- $container: ds
154
- };
155
- providerField.value = {
156
- $type: "StringLiteral",
157
- value: config.provider,
158
- $container: providerField
159
- };
160
- const urlField = {
161
- $type: "ConfigField",
162
- name: "url",
163
- $container: ds
164
- };
165
- const envCall = {
166
- $type: "InvocationExpr",
167
- function: {
168
- $refText: "env"
169
- },
170
- args: [],
171
- $container: urlField
172
- };
173
- const dbUrlArg = {
174
- $type: "Argument"
175
- };
176
- dbUrlArg.value = {
177
- $type: "StringLiteral",
178
- value: "DATABASE_URL",
179
- $container: dbUrlArg
180
- };
181
- envCall.args = [
182
- dbUrlArg
183
- ];
184
- urlField.value = config.provider === "sqlite" ? {
185
- $type: "StringLiteral",
186
- value: "file:./dev.db",
187
- $container: urlField
188
- } : envCall;
189
- ds.fields.push(providerField);
190
- ds.fields.push(urlField);
191
- return zmodel;
192
- }
193
- __name(initializeZmodel, "initializeZmodel");
194
- function getMappedFieldType({ bigint, type }) {
195
- return match(type).with("string", () => ({
196
- type: "String"
197
- })).with("number", () => bigint ? {
198
- type: "BigInt"
199
- } : {
200
- type: "Int"
201
- }).with("boolean", () => ({
202
- type: "Boolean"
203
- })).with("date", () => ({
204
- type: "DateTime"
205
- })).with("json", () => ({
206
- type: "Json"
207
- })).with("string[]", () => ({
208
- type: "String",
209
- array: true
210
- })).with("number[]", () => ({
211
- type: "Int",
212
- array: true
213
- })).when((v) => Array.isArray(v) && v.every((e) => typeof e === "string"), () => {
214
- return {
215
- type: "String"
216
- };
217
- }).otherwise(() => {
218
- throw new Error(`Unsupported field type: ${type}`);
219
- });
220
- }
221
- __name(getMappedFieldType, "getMappedFieldType");
222
- function addOrUpdateModel(tableName, table, zmodel, tables, toManyRelations, numericId) {
223
- let changed = false;
224
- const customModelName = tables[tableName]?.modelName ?? tableName;
225
- const modelName = upperCaseFirst(customModelName);
226
- let dataModel = zmodel.declarations.find((d) => isDataModel(d) && d.name === modelName);
227
- if (!dataModel) {
228
- changed = true;
229
- dataModel = createDataModel(modelName, zmodel, numericId);
230
- zmodel.declarations.push(dataModel);
231
- }
232
- if (modelName !== tableName && !hasAttribute(dataModel, "@@map")) {
233
- addModelAttribute(dataModel, "@@map", [
234
- createStringAttributeArg(tableName)
235
- ]);
236
- }
237
- for (const [fName, field] of Object.entries(table.fields)) {
238
- const fieldName = field.fieldName ?? fName;
239
- if (dataModel.fields.some((f) => f.name === fieldName)) {
240
- continue;
241
- }
242
- changed = true;
243
- if (!field.references) {
244
- const { array, type } = getMappedFieldType(field);
245
- const df = {
246
- $type: "DataField",
247
- name: fieldName,
248
- attributes: [],
249
- comments: [],
250
- $container: dataModel
251
- };
252
- df.type = {
253
- $type: "DataFieldType",
254
- type,
255
- array: !!array,
256
- optional: !field.required,
257
- $container: df
258
- };
259
- dataModel.fields.push(df);
260
- if (fieldName === "id") {
261
- addFieldAttribute(df, "@id");
262
- }
263
- if (field.unique) {
264
- addFieldAttribute(df, "@unique");
265
- }
266
- if (field.defaultValue !== void 0) {
267
- if (fieldName === "createdAt") {
268
- addDefaultNow(df);
269
- } else if (typeof field.defaultValue === "boolean") {
270
- addFieldAttribute(df, "@default", [
271
- createBooleanAttributeArg(field.defaultValue)
272
- ]);
273
- } else if (typeof field.defaultValue === "string") {
274
- addFieldAttribute(df, "@default", [
275
- createStringAttributeArg(field.defaultValue)
276
- ]);
277
- } else if (typeof field.defaultValue === "number") {
278
- addFieldAttribute(df, "@default", [
279
- createNumberAttributeArg(field.defaultValue)
280
- ]);
281
- } else if (typeof field.defaultValue === "function") {
282
- const defaultVal = field.defaultValue();
283
- if (defaultVal instanceof Date) {
284
- addDefaultNow(df);
285
- } else {
286
- console.warn(`Warning: Unsupported default function for field ${fieldName} in model ${table.modelName}. Please adjust manually.`);
287
- }
288
- }
289
- }
290
- if (fieldName === "updatedAt" && field.onUpdate) {
291
- addFieldAttribute(df, "@updatedAt");
292
- } else if (field.onUpdate) {
293
- console.warn(`Warning: 'onUpdate' is only supported on 'updatedAt' fields. Please adjust manually for field ${fieldName} in model ${table.modelName}.`);
294
- }
295
- } else {
296
- addModelField(dataModel, fieldName, numericId ? "Int" : "String", false, !field.required);
297
- const referencedOriginalModelName = field.references.model;
298
- const referencedCustomModelName = tables[referencedOriginalModelName]?.modelName || referencedOriginalModelName;
299
- const relationField = {
300
- $type: "DataField",
301
- name: lowerCaseFirst(referencedCustomModelName),
302
- attributes: [],
303
- comments: [],
304
- $container: dataModel
305
- };
306
- relationField.type = {
307
- $type: "DataFieldType",
308
- reference: {
309
- $refText: upperCaseFirst(referencedCustomModelName)
310
- },
311
- array: field.type.endsWith("[]"),
312
- optional: !field.required,
313
- $container: relationField
314
- };
315
- let action = "Cascade";
316
- if (field.references.onDelete === "no action") action = "NoAction";
317
- else if (field.references.onDelete === "set null") action = "SetNull";
318
- else if (field.references.onDelete === "set default") action = "SetDefault";
319
- else if (field.references.onDelete === "restrict") action = "Restrict";
320
- const relationAttr = {
321
- $type: "DataFieldAttribute",
322
- decl: {
323
- $refText: "@relation"
324
- },
325
- args: [],
326
- $container: relationField
327
- };
328
- const fieldsArg = {
329
- $type: "AttributeArg",
330
- name: "fields",
331
- $container: relationAttr
332
- };
333
- const fieldsExpr = {
334
- $type: "ArrayExpr",
335
- items: [],
336
- $container: fieldsArg
337
- };
338
- const fkRefExpr = {
339
- $type: "ReferenceExpr",
340
- args: [],
341
- $container: fieldsExpr,
342
- target: {
343
- $refText: fieldName
344
- }
345
- };
346
- fieldsExpr.items.push(fkRefExpr);
347
- fieldsArg.value = fieldsExpr;
348
- const referencesArg = {
349
- $type: "AttributeArg",
350
- name: "references",
351
- $container: relationAttr
352
- };
353
- const referencesExpr = {
354
- $type: "ArrayExpr",
355
- items: [],
356
- $container: referencesArg
357
- };
358
- const pkRefExpr = {
359
- $type: "ReferenceExpr",
360
- args: [],
361
- $container: referencesExpr,
362
- target: {
363
- $refText: field.references.field
364
- }
365
- };
366
- referencesExpr.items.push(pkRefExpr);
367
- referencesArg.value = referencesExpr;
368
- const onDeleteArg = {
369
- $type: "AttributeArg",
370
- name: "onDelete",
371
- $container: relationAttr
372
- };
373
- const onDeleteValueExpr = {
374
- $type: "ReferenceExpr",
375
- target: {
376
- $refText: action
377
- },
378
- args: [],
379
- $container: onDeleteArg
380
- };
381
- onDeleteArg.value = onDeleteValueExpr;
382
- relationAttr.args.push(...[
383
- fieldsArg,
384
- referencesArg,
385
- onDeleteArg
386
- ]);
387
- relationField.attributes.push(relationAttr);
388
- dataModel.fields.push(relationField);
389
- }
390
- }
391
- if (toManyRelations.has(modelName)) {
392
- const relations = toManyRelations.get(modelName);
393
- for (const relatedModel of relations) {
394
- const relationName = `${lowerCaseFirst(relatedModel)}s`;
395
- if (!dataModel.fields.some((f) => f.name === relationName)) {
396
- const relationField = {
397
- $type: "DataField",
398
- name: relationName,
399
- attributes: [],
400
- comments: [],
401
- $container: dataModel
402
- };
403
- const relationType = {
404
- $type: "DataFieldType",
405
- reference: {
406
- $refText: relatedModel
407
- },
408
- array: true,
409
- optional: false,
410
- $container: relationField
411
- };
412
- relationField.type = relationType;
413
- dataModel.fields.push(relationField);
414
- }
415
- }
416
- }
417
- return changed;
418
- }
419
- __name(addOrUpdateModel, "addOrUpdateModel");
420
- function addModelAttribute(dataModel, name, args = []) {
421
- const attr = {
422
- $type: "DataModelAttribute",
423
- decl: {
424
- $refText: name
425
- },
426
- $container: dataModel,
427
- args: []
428
- };
429
- const finalArgs = args.map((arg) => ({
430
- ...arg,
431
- $container: attr
432
- }));
433
- attr.args.push(...finalArgs);
434
- dataModel.attributes.push(attr);
435
- }
436
- __name(addModelAttribute, "addModelAttribute");
437
- function addFieldAttribute(dataField, name, args = []) {
438
- const attr = {
439
- $type: "DataFieldAttribute",
440
- decl: {
441
- $refText: name
442
- },
443
- $container: dataField,
444
- args: []
445
- };
446
- const finalArgs = args.map((arg) => ({
447
- ...arg,
448
- $container: attr
449
- }));
450
- attr.args.push(...finalArgs);
451
- dataField.attributes.push(attr);
452
- }
453
- __name(addFieldAttribute, "addFieldAttribute");
454
- function createBooleanAttributeArg(value) {
455
- const arg = {
456
- $type: "AttributeArg"
457
- };
458
- const expr = {
459
- $type: "BooleanLiteral",
460
- value,
461
- $container: arg
462
- };
463
- arg.value = expr;
464
- return arg;
465
- }
466
- __name(createBooleanAttributeArg, "createBooleanAttributeArg");
467
- function createNumberAttributeArg(value) {
468
- const arg = {
469
- $type: "AttributeArg"
470
- };
471
- const expr = {
472
- $type: "NumberLiteral",
473
- value: value.toString(),
474
- $container: arg
475
- };
476
- arg.value = expr;
477
- return arg;
478
- }
479
- __name(createNumberAttributeArg, "createNumberAttributeArg");
480
- function createStringAttributeArg(value) {
481
- const arg = {
482
- $type: "AttributeArg"
483
- };
484
- const expr = {
485
- $type: "StringLiteral",
486
- value,
487
- $container: arg
488
- };
489
- arg.value = expr;
490
- return arg;
491
- }
492
- __name(createStringAttributeArg, "createStringAttributeArg");
493
-
494
- // src/adapter.ts
495
- var zenstackAdapter = /* @__PURE__ */ __name((db, config) => {
496
- let lazyOptions = null;
497
- const createCustomAdapter = /* @__PURE__ */ __name((db2) => ({ getFieldName, options }) => {
498
- const convertSelect = /* @__PURE__ */ __name((select, model) => {
499
- if (!select || !model) return void 0;
500
- return select.reduce((prev, cur) => {
501
- return {
502
- ...prev,
503
- [getFieldName({
504
- model,
505
- field: cur
506
- })]: true
507
- };
508
- }, {});
509
- }, "convertSelect");
510
- function operatorToORMOperator(operator) {
511
- switch (operator) {
512
- case "starts_with":
513
- return "startsWith";
514
- case "ends_with":
515
- return "endsWith";
516
- case "ne":
517
- return "not";
518
- case "not_in":
519
- return "notIn";
520
- default:
521
- return operator;
522
- }
523
- }
524
- __name(operatorToORMOperator, "operatorToORMOperator");
525
- const convertWhereClause = /* @__PURE__ */ __name((model, where) => {
526
- if (!where || !where.length) return {};
527
- if (where.length === 1) {
528
- const w = where[0];
529
- if (!w) {
530
- throw new BetterAuthError("Invalid where clause");
531
- }
532
- return {
533
- [getFieldName({
534
- model,
535
- field: w.field
536
- })]: w.operator === "eq" || !w.operator ? w.value : {
537
- [operatorToORMOperator(w.operator)]: w.value
538
- }
539
- };
540
- }
541
- const and = where.filter((w) => w.connector === "AND" || !w.connector);
542
- const or = where.filter((w) => w.connector === "OR");
543
- const andClause = and.map((w) => {
544
- return {
545
- [getFieldName({
546
- model,
547
- field: w.field
548
- })]: w.operator === "eq" || !w.operator ? w.value : {
549
- [operatorToORMOperator(w.operator)]: w.value
550
- }
551
- };
552
- });
553
- const orClause = or.map((w) => {
554
- return {
555
- [getFieldName({
556
- model,
557
- field: w.field
558
- })]: w.operator === "eq" || !w.operator ? w.value : {
559
- [operatorToORMOperator(w.operator)]: w.value
560
- }
561
- };
562
- });
563
- return {
564
- ...andClause.length ? {
565
- AND: andClause
566
- } : {},
567
- ...orClause.length ? {
568
- OR: orClause
569
- } : {}
570
- };
571
- }, "convertWhereClause");
572
- function requireModelDb(db3, model) {
573
- const modelDb = db3[model];
574
- if (!modelDb) {
575
- throw new BetterAuthError(`Model ${model} does not exist in the database. If you haven't generated the ZenStack schema, you need to run 'npx zen generate'`);
576
- }
577
- return modelDb;
578
- }
579
- __name(requireModelDb, "requireModelDb");
580
- return {
581
- async create({ model, data: values, select }) {
582
- const modelDb = requireModelDb(db2, model);
583
- return await modelDb.create({
584
- data: values,
585
- select: convertSelect(select, model)
586
- });
587
- },
588
- async findOne({ model, where, select }) {
589
- const modelDb = requireModelDb(db2, model);
590
- const whereClause = convertWhereClause(model, where);
591
- return await modelDb.findFirst({
592
- where: whereClause,
593
- select: convertSelect(select, model)
594
- });
595
- },
596
- async findMany({ model, where, limit, offset, sortBy }) {
597
- const modelDb = requireModelDb(db2, model);
598
- const whereClause = convertWhereClause(model, where);
599
- return await modelDb.findMany({
600
- where: whereClause,
601
- take: limit || 100,
602
- skip: offset || 0,
603
- ...sortBy?.field ? {
604
- orderBy: {
605
- [getFieldName({
606
- model,
607
- field: sortBy.field
608
- })]: sortBy.direction === "desc" ? "desc" : "asc"
609
- }
610
- } : {}
611
- });
612
- },
613
- async count({ model, where }) {
614
- const modelDb = requireModelDb(db2, model);
615
- const whereClause = convertWhereClause(model, where);
616
- return await modelDb.count({
617
- where: whereClause
618
- });
619
- },
620
- async update({ model, where, update }) {
621
- const modelDb = requireModelDb(db2, model);
622
- const whereClause = convertWhereClause(model, where);
623
- return await modelDb.update({
624
- where: whereClause,
625
- data: update
626
- });
627
- },
628
- async updateMany({ model, where, update }) {
629
- const modelDb = requireModelDb(db2, model);
630
- const whereClause = convertWhereClause(model, where);
631
- const result = await modelDb.updateMany({
632
- where: whereClause,
633
- data: update
634
- });
635
- return result ? result.count : 0;
636
- },
637
- async delete({ model, where }) {
638
- const modelDb = requireModelDb(db2, model);
639
- const whereClause = convertWhereClause(model, where);
640
- try {
641
- await modelDb.delete({
642
- where: whereClause
643
- });
644
- } catch {
645
- }
646
- },
647
- async deleteMany({ model, where }) {
648
- const modelDb = requireModelDb(db2, model);
649
- const whereClause = convertWhereClause(model, where);
650
- const result = await modelDb.deleteMany({
651
- where: whereClause
652
- });
653
- return result ? result.count : 0;
654
- },
655
- options: config,
656
- createSchema: /* @__PURE__ */ __name(async ({ file, tables }) => {
657
- return generateSchema(file, tables, config, options);
658
- }, "createSchema")
659
- };
660
- }, "createCustomAdapter");
661
- const adapterOptions = {
662
- config: {
663
- adapterId: "zenstack",
664
- adapterName: "ZenStack Adapter",
665
- usePlural: config.usePlural ?? false,
666
- debugLogs: config.debugLogs ?? false,
667
- transaction: /* @__PURE__ */ __name((cb) => db.$transaction((tx) => {
668
- const adapter2 = createAdapterFactory({
669
- config: adapterOptions.config,
670
- adapter: createCustomAdapter(tx)
671
- })(lazyOptions);
672
- return cb(adapter2);
673
- }), "transaction")
674
- },
675
- adapter: createCustomAdapter(db)
676
- };
677
- const adapter = createAdapterFactory(adapterOptions);
678
- return (options) => {
679
- lazyOptions = options;
680
- return adapter(options);
681
- };
682
- }, "zenstackAdapter");
683
- export {
684
- zenstackAdapter
685
- };
686
- //# sourceMappingURL=index.js.map