@saasicat/adapter-drizzle 0.4.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.
package/dist/index.js ADDED
@@ -0,0 +1,1508 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/client.ts
9
+ var DRIZZLE_DB_TOKEN = /* @__PURE__ */ Symbol.for("saasicat/adapter-drizzle/DrizzleDb");
10
+ function resolveDb(client, tx) {
11
+ return tx ?? client;
12
+ }
13
+ __name(resolveDb, "resolveDb");
14
+ function toQuotaMap(value) {
15
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
16
+ return value;
17
+ }
18
+ return {};
19
+ }
20
+ __name(toQuotaMap, "toQuotaMap");
21
+ function toStringArray(value) {
22
+ return Array.isArray(value) ? value : [];
23
+ }
24
+ __name(toStringArray, "toStringArray");
25
+ function escapeLikePattern(value) {
26
+ return value.replace(/[\\%_]/g, "\\$&");
27
+ }
28
+ __name(escapeLikePattern, "escapeLikePattern");
29
+
30
+ // src/async-local-rls-bypass.adapter.ts
31
+ import { Injectable } from "@nestjs/common";
32
+ import { AsyncLocalStorage } from "node:async_hooks";
33
+ function _ts_decorate(decorators, target, key, desc4) {
34
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
35
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
36
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
37
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
38
+ }
39
+ __name(_ts_decorate, "_ts_decorate");
40
+ var AsyncLocalRlsBypassAdapter = class {
41
+ static {
42
+ __name(this, "AsyncLocalRlsBypassAdapter");
43
+ }
44
+ storage = new AsyncLocalStorage();
45
+ async runWithBypass(fn) {
46
+ return this.storage.run({
47
+ bypass: true
48
+ }, fn);
49
+ }
50
+ /** `true` during the execution of a `runWithBypass(...)` callback. */
51
+ isBypassActive() {
52
+ return this.storage.getStore()?.bypass === true;
53
+ }
54
+ };
55
+ AsyncLocalRlsBypassAdapter = _ts_decorate([
56
+ Injectable()
57
+ ], AsyncLocalRlsBypassAdapter);
58
+
59
+ // src/drizzle-audit.adapter.ts
60
+ import { randomUUID } from "node:crypto";
61
+ import { Inject, Injectable as Injectable2 } from "@nestjs/common";
62
+
63
+ // src/schema.ts
64
+ var schema_exports = {};
65
+ __export(schema_exports, {
66
+ auditLogs: () => auditLogs,
67
+ featureCatalogEntries: () => featureCatalogEntries,
68
+ planVersions: () => planVersions,
69
+ plans: () => plans,
70
+ promoCodeRedemptions: () => promoCodeRedemptions,
71
+ promoCodeValidationLogs: () => promoCodeValidationLogs,
72
+ promoCodes: () => promoCodes,
73
+ subscriptions: () => subscriptions,
74
+ superAdminMfa: () => superAdminMfa,
75
+ superAdminUsers: () => superAdminUsers
76
+ });
77
+ import { boolean, integer, jsonb, numeric, pgTable, text, timestamp } from "drizzle-orm/pg-core";
78
+ var ts = /* @__PURE__ */ __name((name) => timestamp(name, {
79
+ precision: 3,
80
+ mode: "date"
81
+ }), "ts");
82
+ var subscriptions = pgTable("subscriptions", {
83
+ id: text("id").primaryKey(),
84
+ tenantId: text("tenantId").notNull(),
85
+ plan: text("plan").notNull(),
86
+ billingCycle: text("billingCycle").notNull().default("YEARLY"),
87
+ status: text("status").notNull().default("TRIAL"),
88
+ trialEntitlementPlan: text("trialEntitlementPlan"),
89
+ pendingPlan: text("pendingPlan"),
90
+ pendingEffectiveAt: ts("pendingEffectiveAt"),
91
+ customLimits: jsonb("customLimits"),
92
+ planVersionId: text("planVersionId"),
93
+ pendingPlanVersionId: text("pendingPlanVersionId"),
94
+ isPilot: boolean("isPilot").notNull().default(false),
95
+ startedAt: ts("startedAt"),
96
+ createdAt: ts("createdAt").notNull().defaultNow(),
97
+ updatedAt: ts("updatedAt").notNull()
98
+ });
99
+ var planVersions = pgTable("plan_versions", {
100
+ id: text("id").primaryKey(),
101
+ planId: text("planId").notNull(),
102
+ version: integer("version").notNull(),
103
+ baseVersionId: text("baseVersionId"),
104
+ features: jsonb("features").notNull(),
105
+ quotas: jsonb("quotas").notNull(),
106
+ monthlyNet: numeric("monthlyNet", {
107
+ precision: 10,
108
+ scale: 2
109
+ }).notNull(),
110
+ yearlyNet: numeric("yearlyNet", {
111
+ precision: 10,
112
+ scale: 2
113
+ }).notNull(),
114
+ marketed: boolean("marketed").notNull().default(true),
115
+ publishedAt: ts("publishedAt"),
116
+ supersededAt: ts("supersededAt"),
117
+ publishedChanges: jsonb("publishedChanges"),
118
+ changeNote: text("changeNote").notNull(),
119
+ nonRegressive: boolean("nonRegressive").notNull().default(true),
120
+ createdByUserId: text("createdByUserId"),
121
+ publishedByUserId: text("publishedByUserId"),
122
+ createdAt: ts("createdAt").notNull().defaultNow(),
123
+ updatedAt: ts("updatedAt").notNull()
124
+ });
125
+ var plans = pgTable("plans", {
126
+ id: text("id").primaryKey(),
127
+ projectKey: text("projectKey").notNull(),
128
+ planKey: text("planKey").notNull(),
129
+ label: text("label").notNull(),
130
+ description: text("description"),
131
+ icon: text("icon"),
132
+ sortOrder: integer("sortOrder").notNull().default(0),
133
+ createdAt: ts("createdAt").notNull().defaultNow(),
134
+ updatedAt: ts("updatedAt").notNull(),
135
+ deletedAt: ts("deletedAt")
136
+ });
137
+ var featureCatalogEntries = pgTable("feature_catalog_entries", {
138
+ id: text("id").primaryKey(),
139
+ projectKey: text("projectKey").notNull(),
140
+ featureKey: text("featureKey").notNull(),
141
+ label: text("label").notNull(),
142
+ description: text("description"),
143
+ marketingLabel: text("marketingLabel"),
144
+ marketingDescription: text("marketingDescription"),
145
+ icon: text("icon"),
146
+ tier: text("tier"),
147
+ core: boolean("core").notNull().default(false),
148
+ requires: text("requires").array(),
149
+ replaces: text("replaces").array(),
150
+ successorKey: text("successorKey"),
151
+ discoveryStatus: text("discoveryStatus").notNull().default("pending"),
152
+ approvedAt: ts("approvedAt"),
153
+ approvedBy: text("approvedBy"),
154
+ approvedSignature: text("approvedSignature"),
155
+ plannedOnly: boolean("plannedOnly").notNull().default(false),
156
+ i18n: jsonb("i18n").notNull().default({}),
157
+ sortOrder: integer("sortOrder").notNull().default(0),
158
+ createdAt: ts("createdAt").notNull().defaultNow(),
159
+ updatedAt: ts("updatedAt").notNull(),
160
+ deletedAt: ts("deletedAt")
161
+ });
162
+ var promoCodes = pgTable("promo_codes", {
163
+ id: text("id").primaryKey(),
164
+ code: text("code").notNull(),
165
+ valueType: text("valueType").notNull(),
166
+ value: numeric("value", {
167
+ precision: 8,
168
+ scale: 2
169
+ }).notNull(),
170
+ durationType: text("durationType").notNull().default("ONCE"),
171
+ durationValue: integer("durationValue"),
172
+ validFrom: ts("validFrom"),
173
+ validUntil: ts("validUntil"),
174
+ maxRedemptions: integer("maxRedemptions"),
175
+ redemptionsCount: integer("redemptionsCount").notNull().default(0),
176
+ appliesToPlans: text("appliesToPlans").array(),
177
+ appliesToBilling: text("appliesToBilling"),
178
+ firstTimeCustomersOnly: boolean("firstTimeCustomersOnly").notNull().default(true),
179
+ minimumPlanAmountGross: numeric("minimumPlanAmountGross", {
180
+ precision: 10,
181
+ scale: 2
182
+ }),
183
+ allowZeroInvoice: boolean("allowZeroInvoice").notNull().default(false),
184
+ status: text("status").notNull().default("ACTIVE"),
185
+ description: text("description"),
186
+ campaignTag: text("campaignTag"),
187
+ revenueDeductionAccount: text("revenueDeductionAccount"),
188
+ createdById: text("createdById").notNull(),
189
+ createdAt: ts("createdAt").notNull().defaultNow(),
190
+ updatedAt: ts("updatedAt").notNull(),
191
+ deletedAt: ts("deletedAt")
192
+ });
193
+ var promoCodeRedemptions = pgTable("promo_code_redemptions", {
194
+ id: text("id").primaryKey(),
195
+ promoCodeId: text("promoCodeId").notNull(),
196
+ subscriptionId: text("subscriptionId").notNull(),
197
+ tenantId: text("tenantId").notNull(),
198
+ appliedValueType: text("appliedValueType").notNull(),
199
+ appliedValue: numeric("appliedValue", {
200
+ precision: 8,
201
+ scale: 2
202
+ }).notNull(),
203
+ appliedDurationType: text("appliedDurationType").notNull(),
204
+ appliedDurationValue: integer("appliedDurationValue"),
205
+ startsAt: ts("startsAt").notNull(),
206
+ endsAt: ts("endsAt"),
207
+ status: text("status").notNull().default("ACTIVE"),
208
+ redeemedAt: ts("redeemedAt").notNull().defaultNow(),
209
+ reversedAt: ts("reversedAt")
210
+ });
211
+ var promoCodeValidationLogs = pgTable("promo_code_validation_logs", {
212
+ id: text("id").primaryKey(),
213
+ promoCodeId: text("promoCodeId"),
214
+ codeAttempt: text("codeAttempt").notNull(),
215
+ ipHash: text("ipHash"),
216
+ sessionId: text("sessionId"),
217
+ result: text("result").notNull(),
218
+ createdAt: ts("createdAt").notNull().defaultNow()
219
+ });
220
+ var auditLogs = pgTable("audit_logs", {
221
+ id: text("id").primaryKey(),
222
+ tenantId: text("tenantId"),
223
+ userId: text("userId"),
224
+ entity: text("entity").notNull(),
225
+ entityId: text("entityId").notNull(),
226
+ action: text("action").notNull(),
227
+ changes: jsonb("changes"),
228
+ actorTag: text("actorTag"),
229
+ ipAddress: text("ipAddress"),
230
+ userAgent: text("userAgent"),
231
+ createdAt: ts("createdAt").notNull().defaultNow()
232
+ });
233
+ var superAdminUsers = pgTable("super_admin_users", {
234
+ id: text("id").primaryKey(),
235
+ email: text("email").notNull(),
236
+ passwordHash: text("passwordHash").notNull(),
237
+ firstName: text("firstName"),
238
+ lastName: text("lastName"),
239
+ platformRole: text("platformRole").notNull().default("SUPER_ADMIN"),
240
+ isActive: boolean("isActive").notNull().default(true),
241
+ lastLoginAt: ts("lastLoginAt"),
242
+ deletedAt: ts("deletedAt"),
243
+ createdAt: ts("createdAt").notNull().defaultNow(),
244
+ updatedAt: ts("updatedAt").notNull()
245
+ });
246
+ var superAdminMfa = pgTable("super_admin_mfa", {
247
+ userId: text("userId").primaryKey(),
248
+ secret: text("secret"),
249
+ enabledAt: ts("enabledAt"),
250
+ updatedAt: ts("updatedAt").notNull()
251
+ });
252
+
253
+ // src/drizzle-audit.adapter.ts
254
+ function _ts_decorate2(decorators, target, key, desc4) {
255
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
256
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
257
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
258
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
259
+ }
260
+ __name(_ts_decorate2, "_ts_decorate");
261
+ function _ts_metadata(k, v) {
262
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
263
+ }
264
+ __name(_ts_metadata, "_ts_metadata");
265
+ function _ts_param(paramIndex, decorator) {
266
+ return function(target, key) {
267
+ decorator(target, key, paramIndex);
268
+ };
269
+ }
270
+ __name(_ts_param, "_ts_param");
271
+ function buildActorTag(actor) {
272
+ return `${actor.source}:${actor.email}:${actor.context}`;
273
+ }
274
+ __name(buildActorTag, "buildActorTag");
275
+ var DrizzleAuditAdapter = class {
276
+ static {
277
+ __name(this, "DrizzleAuditAdapter");
278
+ }
279
+ db;
280
+ constructor(db) {
281
+ this.db = db;
282
+ }
283
+ async write(input) {
284
+ await this.db.insert(auditLogs).values({
285
+ id: randomUUID(),
286
+ tenantId: null,
287
+ userId: input.actor.userId,
288
+ entity: input.entity,
289
+ entityId: input.entityId,
290
+ action: input.action,
291
+ changes: input.changes ?? {},
292
+ actorTag: buildActorTag(input.actor)
293
+ });
294
+ }
295
+ };
296
+ DrizzleAuditAdapter = _ts_decorate2([
297
+ Injectable2(),
298
+ _ts_param(0, Inject(DRIZZLE_DB_TOKEN)),
299
+ _ts_metadata("design:type", Function),
300
+ _ts_metadata("design:paramtypes", [
301
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
302
+ ])
303
+ ], DrizzleAuditAdapter);
304
+
305
+ // src/drizzle-audit-query.adapter.ts
306
+ import { Inject as Inject2, Injectable as Injectable3 } from "@nestjs/common";
307
+ import { and, desc, eq, gte, like, lte } from "drizzle-orm";
308
+ function _ts_decorate3(decorators, target, key, desc4) {
309
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
310
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
311
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
312
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
313
+ }
314
+ __name(_ts_decorate3, "_ts_decorate");
315
+ function _ts_metadata2(k, v) {
316
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
317
+ }
318
+ __name(_ts_metadata2, "_ts_metadata");
319
+ function _ts_param2(paramIndex, decorator) {
320
+ return function(target, key) {
321
+ decorator(target, key, paramIndex);
322
+ };
323
+ }
324
+ __name(_ts_param2, "_ts_param");
325
+ var DEFAULT_PAGE_SIZE = 50;
326
+ var MAX_PAGE_SIZE = 200;
327
+ var DrizzleAuditQueryAdapter = class {
328
+ static {
329
+ __name(this, "DrizzleAuditQueryAdapter");
330
+ }
331
+ db;
332
+ constructor(db) {
333
+ this.db = db;
334
+ }
335
+ async list(filter) {
336
+ const page = Math.max(filter.page ?? 1, 1);
337
+ const pageSize = Math.min(Math.max(filter.pageSize ?? DEFAULT_PAGE_SIZE, 1), MAX_PAGE_SIZE);
338
+ const conditions = [
339
+ filter.tenantId ? eq(auditLogs.tenantId, filter.tenantId) : void 0,
340
+ filter.userId ? eq(auditLogs.userId, filter.userId) : void 0,
341
+ filter.entity ? eq(auditLogs.entity, filter.entity) : void 0,
342
+ filter.entityId ? eq(auditLogs.entityId, filter.entityId) : void 0,
343
+ filter.action ? eq(auditLogs.action, filter.action) : void 0,
344
+ toActorTagCondition(filter.actorTag),
345
+ filter.from ? gte(auditLogs.createdAt, new Date(filter.from)) : void 0,
346
+ filter.to ? lte(auditLogs.createdAt, new Date(filter.to)) : void 0
347
+ ];
348
+ const rows = await this.db.select().from(auditLogs).where(and(...conditions)).orderBy(desc(auditLogs.createdAt)).limit(pageSize).offset((page - 1) * pageSize);
349
+ return rows.map(toAuditEntry);
350
+ }
351
+ };
352
+ DrizzleAuditQueryAdapter = _ts_decorate3([
353
+ Injectable3(),
354
+ _ts_param2(0, Inject2(DRIZZLE_DB_TOKEN)),
355
+ _ts_metadata2("design:type", Function),
356
+ _ts_metadata2("design:paramtypes", [
357
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
358
+ ])
359
+ ], DrizzleAuditQueryAdapter);
360
+ function toActorTagCondition(actorTag) {
361
+ if (!actorTag) return void 0;
362
+ if (actorTag.endsWith("*")) {
363
+ return like(auditLogs.actorTag, `${escapeLikePattern(actorTag.slice(0, -1))}%`);
364
+ }
365
+ return eq(auditLogs.actorTag, actorTag);
366
+ }
367
+ __name(toActorTagCondition, "toActorTagCondition");
368
+ function toAuditEntry(row) {
369
+ return {
370
+ id: row.id,
371
+ tenantId: row.tenantId,
372
+ userId: row.userId,
373
+ // The schema does not persist the email — the actorTag carries it.
374
+ userEmail: row.actorTag?.split(":")[1] ?? null,
375
+ entity: row.entity,
376
+ entityId: row.entityId,
377
+ action: row.action,
378
+ changes: row.changes ?? null,
379
+ actorTag: row.actorTag,
380
+ ipAddress: row.ipAddress,
381
+ userAgent: row.userAgent,
382
+ createdAt: row.createdAt.toISOString()
383
+ };
384
+ }
385
+ __name(toAuditEntry, "toAuditEntry");
386
+
387
+ // src/drizzle-audit-stats.adapter.ts
388
+ import { Inject as Inject3, Injectable as Injectable4 } from "@nestjs/common";
389
+ import { count, gte as gte2 } from "drizzle-orm";
390
+ function _ts_decorate4(decorators, target, key, desc4) {
391
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
392
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
393
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
394
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
395
+ }
396
+ __name(_ts_decorate4, "_ts_decorate");
397
+ function _ts_metadata3(k, v) {
398
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
399
+ }
400
+ __name(_ts_metadata3, "_ts_metadata");
401
+ function _ts_param3(paramIndex, decorator) {
402
+ return function(target, key) {
403
+ decorator(target, key, paramIndex);
404
+ };
405
+ }
406
+ __name(_ts_param3, "_ts_param");
407
+ var DrizzleAuditStatsAdapter = class {
408
+ static {
409
+ __name(this, "DrizzleAuditStatsAdapter");
410
+ }
411
+ db;
412
+ constructor(db) {
413
+ this.db = db;
414
+ }
415
+ async countSince(since) {
416
+ const rows = await this.db.select({
417
+ value: count()
418
+ }).from(auditLogs).where(gte2(auditLogs.createdAt, since));
419
+ return rows[0]?.value ?? 0;
420
+ }
421
+ };
422
+ DrizzleAuditStatsAdapter = _ts_decorate4([
423
+ Injectable4(),
424
+ _ts_param3(0, Inject3(DRIZZLE_DB_TOKEN)),
425
+ _ts_metadata3("design:type", Function),
426
+ _ts_metadata3("design:paramtypes", [
427
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
428
+ ])
429
+ ], DrizzleAuditStatsAdapter);
430
+
431
+ // src/drizzle-mfa.adapter.ts
432
+ import { Inject as Inject4, Injectable as Injectable5 } from "@nestjs/common";
433
+ import { eq as eq2 } from "drizzle-orm";
434
+ function _ts_decorate5(decorators, target, key, desc4) {
435
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
436
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
437
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
438
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
439
+ }
440
+ __name(_ts_decorate5, "_ts_decorate");
441
+ function _ts_metadata4(k, v) {
442
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
443
+ }
444
+ __name(_ts_metadata4, "_ts_metadata");
445
+ function _ts_param4(paramIndex, decorator) {
446
+ return function(target, key) {
447
+ decorator(target, key, paramIndex);
448
+ };
449
+ }
450
+ __name(_ts_param4, "_ts_param");
451
+ var DrizzleMfaAdapter = class {
452
+ static {
453
+ __name(this, "DrizzleMfaAdapter");
454
+ }
455
+ db;
456
+ constructor(db) {
457
+ this.db = db;
458
+ }
459
+ async getSecret(userId) {
460
+ const rows = await this.db.select().from(superAdminMfa).where(eq2(superAdminMfa.userId, userId)).limit(1);
461
+ return rows[0]?.secret ?? null;
462
+ }
463
+ async setSecret(userId, secret) {
464
+ const enabledAt = secret ? /* @__PURE__ */ new Date() : null;
465
+ await this.db.insert(superAdminMfa).values({
466
+ userId,
467
+ secret,
468
+ enabledAt,
469
+ updatedAt: /* @__PURE__ */ new Date()
470
+ }).onConflictDoUpdate({
471
+ target: superAdminMfa.userId,
472
+ set: {
473
+ secret,
474
+ enabledAt,
475
+ updatedAt: /* @__PURE__ */ new Date()
476
+ }
477
+ });
478
+ }
479
+ async isEnabled(userId) {
480
+ const rows = await this.db.select().from(superAdminMfa).where(eq2(superAdminMfa.userId, userId)).limit(1);
481
+ const row = rows[0];
482
+ return !!row?.secret && !!row?.enabledAt;
483
+ }
484
+ };
485
+ DrizzleMfaAdapter = _ts_decorate5([
486
+ Injectable5(),
487
+ _ts_param4(0, Inject4(DRIZZLE_DB_TOKEN)),
488
+ _ts_metadata4("design:type", Function),
489
+ _ts_metadata4("design:paramtypes", [
490
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
491
+ ])
492
+ ], DrizzleMfaAdapter);
493
+
494
+ // src/drizzle-plan-catalog-import-sink.ts
495
+ import { randomUUID as randomUUID2 } from "node:crypto";
496
+ import { Inject as Inject5, Injectable as Injectable6 } from "@nestjs/common";
497
+ import { and as and2, eq as eq3, isNotNull, isNull, lt } from "drizzle-orm";
498
+ function _ts_decorate6(decorators, target, key, desc4) {
499
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
500
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
501
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
502
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
503
+ }
504
+ __name(_ts_decorate6, "_ts_decorate");
505
+ function _ts_metadata5(k, v) {
506
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
507
+ }
508
+ __name(_ts_metadata5, "_ts_metadata");
509
+ function _ts_param5(paramIndex, decorator) {
510
+ return function(target, key) {
511
+ decorator(target, key, paramIndex);
512
+ };
513
+ }
514
+ __name(_ts_param5, "_ts_param");
515
+ var DrizzlePlanCatalogImportSink = class {
516
+ static {
517
+ __name(this, "DrizzlePlanCatalogImportSink");
518
+ }
519
+ db;
520
+ constructor(db) {
521
+ this.db = db;
522
+ }
523
+ async upsertPlan(input) {
524
+ const existing = await this.db.select({
525
+ id: plans.id
526
+ }).from(plans).where(and2(eq3(plans.projectKey, input.projectKey), eq3(plans.planKey, input.planKey))).limit(1);
527
+ if (existing[0]) return {
528
+ created: false,
529
+ skipReason: "exists"
530
+ };
531
+ await this.db.insert(plans).values({
532
+ id: randomUUID2(),
533
+ projectKey: input.projectKey,
534
+ planKey: input.planKey,
535
+ label: input.label,
536
+ description: input.description ?? null,
537
+ sortOrder: input.sortOrder ?? 0,
538
+ updatedAt: /* @__PURE__ */ new Date()
539
+ });
540
+ return {
541
+ created: true
542
+ };
543
+ }
544
+ async upsertPlanVersion(input) {
545
+ const existing = await this.db.select({
546
+ id: planVersions.id
547
+ }).from(planVersions).where(and2(eq3(planVersions.planId, input.planKey), eq3(planVersions.version, input.version))).limit(1);
548
+ if (existing[0]) return {
549
+ created: false,
550
+ skipReason: "exists"
551
+ };
552
+ const now = /* @__PURE__ */ new Date();
553
+ if (input.publish) {
554
+ await this.db.update(planVersions).set({
555
+ supersededAt: now,
556
+ updatedAt: now
557
+ }).where(and2(eq3(planVersions.planId, input.planKey), isNotNull(planVersions.publishedAt), isNull(planVersions.supersededAt), lt(planVersions.version, input.version)));
558
+ }
559
+ await this.db.insert(planVersions).values({
560
+ id: randomUUID2(),
561
+ planId: input.planKey,
562
+ version: input.version,
563
+ features: input.features,
564
+ quotas: input.quotas,
565
+ monthlyNet: input.monthlyNet,
566
+ yearlyNet: input.yearlyNet,
567
+ marketed: input.marketed,
568
+ publishedAt: input.publish ? now : null,
569
+ changeNote: input.changeNote,
570
+ updatedAt: now
571
+ });
572
+ return {
573
+ created: true
574
+ };
575
+ }
576
+ async upsertFeatureCatalogEntry(input) {
577
+ const existing = await this.db.select({
578
+ id: featureCatalogEntries.id
579
+ }).from(featureCatalogEntries).where(and2(eq3(featureCatalogEntries.projectKey, input.projectKey), eq3(featureCatalogEntries.featureKey, input.featureKey))).limit(1);
580
+ if (existing[0]) return {
581
+ created: false,
582
+ skipReason: "exists"
583
+ };
584
+ await this.db.insert(featureCatalogEntries).values({
585
+ id: randomUUID2(),
586
+ projectKey: input.projectKey,
587
+ featureKey: input.featureKey,
588
+ label: input.label ?? input.featureKey,
589
+ icon: input.icon ?? null,
590
+ tier: input.tier ?? null,
591
+ plannedOnly: input.plannedOnly ?? false,
592
+ core: input.core ?? false,
593
+ updatedAt: /* @__PURE__ */ new Date()
594
+ });
595
+ return {
596
+ created: true
597
+ };
598
+ }
599
+ };
600
+ DrizzlePlanCatalogImportSink = _ts_decorate6([
601
+ Injectable6(),
602
+ _ts_param5(0, Inject5(DRIZZLE_DB_TOKEN)),
603
+ _ts_metadata5("design:type", Function),
604
+ _ts_metadata5("design:paramtypes", [
605
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
606
+ ])
607
+ ], DrizzlePlanCatalogImportSink);
608
+
609
+ // src/drizzle-plan-catalog-read-sink.ts
610
+ import { Inject as Inject6, Injectable as Injectable7 } from "@nestjs/common";
611
+ import { and as and3, asc, eq as eq4, inArray, isNotNull as isNotNull2, isNull as isNull2 } from "drizzle-orm";
612
+ function _ts_decorate7(decorators, target, key, desc4) {
613
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
614
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
615
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
616
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
617
+ }
618
+ __name(_ts_decorate7, "_ts_decorate");
619
+ function _ts_metadata6(k, v) {
620
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
621
+ }
622
+ __name(_ts_metadata6, "_ts_metadata");
623
+ function _ts_param6(paramIndex, decorator) {
624
+ return function(target, key) {
625
+ decorator(target, key, paramIndex);
626
+ };
627
+ }
628
+ __name(_ts_param6, "_ts_param");
629
+ var DrizzlePlanCatalogReadSink = class {
630
+ static {
631
+ __name(this, "DrizzlePlanCatalogReadSink");
632
+ }
633
+ db;
634
+ constructor(db) {
635
+ this.db = db;
636
+ }
637
+ async loadSnapshot(projectKey) {
638
+ const planRows = await this.db.select().from(plans).where(and3(eq4(plans.projectKey, projectKey), isNull2(plans.deletedAt))).orderBy(asc(plans.sortOrder));
639
+ const planKeys = planRows.map((plan) => plan.planKey);
640
+ const liveVersionRows = planKeys.length === 0 ? [] : await this.db.select().from(planVersions).where(and3(inArray(planVersions.planId, planKeys), isNotNull2(planVersions.publishedAt), isNull2(planVersions.supersededAt)));
641
+ const featureRows = await this.db.select().from(featureCatalogEntries).where(and3(eq4(featureCatalogEntries.projectKey, projectKey), isNull2(featureCatalogEntries.deletedAt))).orderBy(asc(featureCatalogEntries.sortOrder));
642
+ return {
643
+ plans: planRows.map(toPlanRow),
644
+ livePlanVersions: liveVersionRows.map(toPlanVersionRow),
645
+ featureEntries: featureRows.map(toFeatureCatalogEntryRow)
646
+ };
647
+ }
648
+ };
649
+ DrizzlePlanCatalogReadSink = _ts_decorate7([
650
+ Injectable7(),
651
+ _ts_param6(0, Inject6(DRIZZLE_DB_TOKEN)),
652
+ _ts_metadata6("design:type", Function),
653
+ _ts_metadata6("design:paramtypes", [
654
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
655
+ ])
656
+ ], DrizzlePlanCatalogReadSink);
657
+ function toPlanRow(row) {
658
+ return {
659
+ id: row.id,
660
+ projectKey: row.projectKey,
661
+ planKey: row.planKey,
662
+ label: row.label,
663
+ description: row.description,
664
+ icon: row.icon,
665
+ sortOrder: row.sortOrder,
666
+ createdAt: row.createdAt.toISOString(),
667
+ updatedAt: row.updatedAt.toISOString(),
668
+ deletedAt: row.deletedAt ? row.deletedAt.toISOString() : null
669
+ };
670
+ }
671
+ __name(toPlanRow, "toPlanRow");
672
+ function toPlanVersionRow(row) {
673
+ return {
674
+ id: row.id,
675
+ planId: row.planId,
676
+ version: row.version,
677
+ baseVersionId: row.baseVersionId,
678
+ publishedAt: row.publishedAt ? row.publishedAt.toISOString() : null,
679
+ supersededAt: row.supersededAt ? row.supersededAt.toISOString() : null,
680
+ publishedChanges: row.publishedChanges ?? null,
681
+ changeNote: row.changeNote,
682
+ nonRegressive: row.nonRegressive,
683
+ validFrom: null,
684
+ validUntil: null,
685
+ createdByUserId: row.createdByUserId,
686
+ publishedByUserId: row.publishedByUserId,
687
+ createdAt: row.createdAt.toISOString(),
688
+ updatedAt: row.updatedAt.toISOString(),
689
+ features: toStringArray(row.features),
690
+ quotas: toQuotaMap(row.quotas),
691
+ monthlyNet: String(row.monthlyNet),
692
+ yearlyNet: String(row.yearlyNet),
693
+ marketed: row.marketed
694
+ };
695
+ }
696
+ __name(toPlanVersionRow, "toPlanVersionRow");
697
+ function toFeatureCatalogEntryRow(row) {
698
+ return {
699
+ id: row.id,
700
+ projectKey: row.projectKey,
701
+ featureKey: row.featureKey,
702
+ label: row.label,
703
+ description: row.description,
704
+ marketingLabel: row.marketingLabel,
705
+ marketingDescription: row.marketingDescription,
706
+ icon: row.icon,
707
+ tier: row.tier,
708
+ discoveryStatus: row.discoveryStatus,
709
+ requires: row.requires ?? [],
710
+ replaces: row.replaces ?? [],
711
+ successorKey: row.successorKey,
712
+ approvedAt: row.approvedAt ? row.approvedAt.toISOString() : null,
713
+ approvedBy: row.approvedBy,
714
+ approvedSignature: row.approvedSignature,
715
+ plannedOnly: row.plannedOnly,
716
+ core: row.core,
717
+ i18n: row.i18n ?? {},
718
+ sortOrder: row.sortOrder,
719
+ createdAt: row.createdAt.toISOString(),
720
+ updatedAt: row.updatedAt.toISOString(),
721
+ deletedAt: row.deletedAt ? row.deletedAt.toISOString() : null
722
+ };
723
+ }
724
+ __name(toFeatureCatalogEntryRow, "toFeatureCatalogEntryRow");
725
+
726
+ // src/drizzle-plan-version.repository.ts
727
+ import { Inject as Inject7, Injectable as Injectable8 } from "@nestjs/common";
728
+ import { and as and4, desc as desc2, eq as eq5, isNotNull as isNotNull3, isNull as isNull3 } from "drizzle-orm";
729
+ function _ts_decorate8(decorators, target, key, desc4) {
730
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
731
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
732
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
733
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
734
+ }
735
+ __name(_ts_decorate8, "_ts_decorate");
736
+ function _ts_metadata7(k, v) {
737
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
738
+ }
739
+ __name(_ts_metadata7, "_ts_metadata");
740
+ function _ts_param7(paramIndex, decorator) {
741
+ return function(target, key) {
742
+ decorator(target, key, paramIndex);
743
+ };
744
+ }
745
+ __name(_ts_param7, "_ts_param");
746
+ var DrizzlePlanVersionRepository = class {
747
+ static {
748
+ __name(this, "DrizzlePlanVersionRepository");
749
+ }
750
+ db;
751
+ constructor(db) {
752
+ this.db = db;
753
+ }
754
+ async findLatestLive(planId, tx) {
755
+ const db = resolveDb(this.db, tx);
756
+ const rows = await db.select().from(planVersions).where(and4(eq5(planVersions.planId, planId), isNotNull3(planVersions.publishedAt), isNull3(planVersions.supersededAt))).orderBy(desc2(planVersions.version)).limit(1);
757
+ const row = rows[0];
758
+ if (!row) return null;
759
+ return {
760
+ planId: row.planId,
761
+ quotas: toQuotaMap(row.quotas),
762
+ features: toStringArray(row.features)
763
+ };
764
+ }
765
+ };
766
+ DrizzlePlanVersionRepository = _ts_decorate8([
767
+ Injectable8(),
768
+ _ts_param7(0, Inject7(DRIZZLE_DB_TOKEN)),
769
+ _ts_metadata7("design:type", Function),
770
+ _ts_metadata7("design:paramtypes", [
771
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
772
+ ])
773
+ ], DrizzlePlanVersionRepository);
774
+
775
+ // src/drizzle-promo-code-redemption.repository.ts
776
+ import { randomUUID as randomUUID3 } from "node:crypto";
777
+ import { Inject as Inject8, Injectable as Injectable9 } from "@nestjs/common";
778
+ import { and as and5, desc as desc3, eq as eq6, lt as lt2 } from "drizzle-orm";
779
+ function _ts_decorate9(decorators, target, key, desc4) {
780
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
781
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
782
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
783
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
784
+ }
785
+ __name(_ts_decorate9, "_ts_decorate");
786
+ function _ts_metadata8(k, v) {
787
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
788
+ }
789
+ __name(_ts_metadata8, "_ts_metadata");
790
+ function _ts_param8(paramIndex, decorator) {
791
+ return function(target, key) {
792
+ decorator(target, key, paramIndex);
793
+ };
794
+ }
795
+ __name(_ts_param8, "_ts_param");
796
+ var DrizzlePromoCodeRedemptionRepository = class {
797
+ static {
798
+ __name(this, "DrizzlePromoCodeRedemptionRepository");
799
+ }
800
+ db;
801
+ constructor(db) {
802
+ this.db = db;
803
+ }
804
+ async findBySubscription(subscriptionId, tx) {
805
+ const db = resolveDb(this.db, tx);
806
+ const rows = await db.select().from(promoCodeRedemptions).where(eq6(promoCodeRedemptions.subscriptionId, subscriptionId)).limit(1);
807
+ const row = rows[0];
808
+ return row ? toRecord(row) : null;
809
+ }
810
+ async create(data, tx) {
811
+ const db = resolveDb(this.db, tx);
812
+ const rows = await db.insert(promoCodeRedemptions).values({
813
+ id: randomUUID3(),
814
+ promoCodeId: data.promoCodeId,
815
+ subscriptionId: data.subscriptionId,
816
+ tenantId: data.tenantId,
817
+ appliedValueType: data.appliedValueType,
818
+ appliedValue: data.appliedValue,
819
+ appliedDurationType: data.appliedDurationType,
820
+ appliedDurationValue: data.appliedDurationValue,
821
+ startsAt: data.startsAt,
822
+ endsAt: data.endsAt
823
+ }).returning();
824
+ return toRecord(rows[0]);
825
+ }
826
+ async setReversed(id, tx) {
827
+ const db = resolveDb(this.db, tx);
828
+ const rows = await db.update(promoCodeRedemptions).set({
829
+ status: "REVERSED",
830
+ reversedAt: /* @__PURE__ */ new Date()
831
+ }).where(eq6(promoCodeRedemptions.id, id)).returning();
832
+ const row = rows[0];
833
+ if (!row) {
834
+ throw new Error(`PromoCodeRedemption ${id} not found.`);
835
+ }
836
+ return toRecord(row);
837
+ }
838
+ async countByPromoCode(promoCodeId, status) {
839
+ const rows = await this.db.select({
840
+ id: promoCodeRedemptions.id
841
+ }).from(promoCodeRedemptions).where(and5(eq6(promoCodeRedemptions.promoCodeId, promoCodeId), status ? eq6(promoCodeRedemptions.status, status) : void 0));
842
+ return rows.length;
843
+ }
844
+ async listByPromoCode(promoCodeId) {
845
+ const rows = await this.db.select().from(promoCodeRedemptions).where(eq6(promoCodeRedemptions.promoCodeId, promoCodeId)).orderBy(desc3(promoCodeRedemptions.redeemedAt));
846
+ return rows.map(toRecord);
847
+ }
848
+ async expireDueRedemptions(now) {
849
+ const expired = await this.db.update(promoCodeRedemptions).set({
850
+ status: "EXPIRED"
851
+ }).where(and5(eq6(promoCodeRedemptions.status, "ACTIVE"), lt2(promoCodeRedemptions.endsAt, now))).returning({
852
+ id: promoCodeRedemptions.id
853
+ });
854
+ return expired.length;
855
+ }
856
+ };
857
+ DrizzlePromoCodeRedemptionRepository = _ts_decorate9([
858
+ Injectable9(),
859
+ _ts_param8(0, Inject8(DRIZZLE_DB_TOKEN)),
860
+ _ts_metadata8("design:type", Function),
861
+ _ts_metadata8("design:paramtypes", [
862
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
863
+ ])
864
+ ], DrizzlePromoCodeRedemptionRepository);
865
+ function toRecord(row) {
866
+ return {
867
+ id: row.id,
868
+ promoCodeId: row.promoCodeId,
869
+ subscriptionId: row.subscriptionId,
870
+ tenantId: row.tenantId,
871
+ appliedValueType: row.appliedValueType,
872
+ appliedValue: String(row.appliedValue),
873
+ appliedDurationType: row.appliedDurationType,
874
+ appliedDurationValue: row.appliedDurationValue,
875
+ startsAt: row.startsAt,
876
+ endsAt: row.endsAt,
877
+ status: row.status,
878
+ redeemedAt: row.redeemedAt,
879
+ reversedAt: row.reversedAt
880
+ };
881
+ }
882
+ __name(toRecord, "toRecord");
883
+
884
+ // src/drizzle-promo-code.repository.ts
885
+ import { randomUUID as randomUUID4 } from "node:crypto";
886
+ import { Inject as Inject9, Injectable as Injectable10 } from "@nestjs/common";
887
+ import { and as and6, eq as eq7, gte as gte3, inArray as inArray2, isNotNull as isNotNull4, isNull as isNull4, like as like2, lt as lt3, or, sql } from "drizzle-orm";
888
+ function _ts_decorate10(decorators, target, key, desc4) {
889
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
890
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
891
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
892
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
893
+ }
894
+ __name(_ts_decorate10, "_ts_decorate");
895
+ function _ts_metadata9(k, v) {
896
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
897
+ }
898
+ __name(_ts_metadata9, "_ts_metadata");
899
+ function _ts_param9(paramIndex, decorator) {
900
+ return function(target, key) {
901
+ decorator(target, key, paramIndex);
902
+ };
903
+ }
904
+ __name(_ts_param9, "_ts_param");
905
+ var DrizzlePromoCodeRepository = class {
906
+ static {
907
+ __name(this, "DrizzlePromoCodeRepository");
908
+ }
909
+ db;
910
+ constructor(db) {
911
+ this.db = db;
912
+ }
913
+ async findById(id) {
914
+ const rows = await this.db.select().from(promoCodes).where(eq7(promoCodes.id, id)).limit(1);
915
+ const row = rows[0];
916
+ return row ? toRecord2(row) : null;
917
+ }
918
+ async findByCode(code, tx) {
919
+ const db = resolveDb(this.db, tx);
920
+ const rows = await db.select().from(promoCodes).where(eq7(promoCodes.code, normalizeCode(code))).limit(1);
921
+ const row = rows[0];
922
+ if (!row || row.deletedAt) return null;
923
+ return toRecord2(row);
924
+ }
925
+ async findMany(filter) {
926
+ const conditions = [
927
+ isNull4(promoCodes.deletedAt),
928
+ filter.status ? eq7(promoCodes.status, filter.status) : void 0,
929
+ filter.campaignTag ? eq7(promoCodes.campaignTag, filter.campaignTag) : void 0,
930
+ filter.search ? like2(promoCodes.code, `%${escapeLikePattern(normalizeCode(filter.search))}%`) : void 0
931
+ ];
932
+ const rows = await this.db.select().from(promoCodes).where(and6(...conditions)).orderBy(sql`${promoCodes.createdAt} DESC`);
933
+ return rows.map(toRecord2);
934
+ }
935
+ async create(data) {
936
+ const rows = await this.db.insert(promoCodes).values({
937
+ id: randomUUID4(),
938
+ code: normalizeCode(data.code),
939
+ valueType: data.valueType,
940
+ value: data.value.toFixed(2),
941
+ durationType: data.durationType,
942
+ durationValue: data.durationValue ?? null,
943
+ validFrom: data.validFrom ?? null,
944
+ validUntil: data.validUntil ?? null,
945
+ maxRedemptions: data.maxRedemptions ?? null,
946
+ appliesToPlans: data.appliesToPlans ?? [],
947
+ appliesToBilling: data.appliesToBilling ?? null,
948
+ firstTimeCustomersOnly: data.firstTimeCustomersOnly ?? true,
949
+ minimumPlanAmountGross: data.minimumPlanAmountGross?.toFixed(2) ?? null,
950
+ allowZeroInvoice: data.allowZeroInvoice ?? false,
951
+ description: data.description ?? null,
952
+ campaignTag: data.campaignTag ?? null,
953
+ revenueDeductionAccount: data.revenueDeductionAccount ?? null,
954
+ createdById: data.createdById,
955
+ updatedAt: /* @__PURE__ */ new Date()
956
+ }).returning();
957
+ return toRecord2(rows[0]);
958
+ }
959
+ async update(id, data) {
960
+ const rows = await this.db.update(promoCodes).set({
961
+ status: data.status,
962
+ description: data.description,
963
+ validUntil: data.validUntil,
964
+ maxRedemptions: data.maxRedemptions,
965
+ updatedAt: /* @__PURE__ */ new Date()
966
+ }).where(eq7(promoCodes.id, id)).returning();
967
+ const row = rows[0];
968
+ if (!row) {
969
+ throw new Error(`PromoCode ${id} not found.`);
970
+ }
971
+ return toRecord2(row);
972
+ }
973
+ async softDelete(id) {
974
+ await this.db.update(promoCodes).set({
975
+ deletedAt: /* @__PURE__ */ new Date(),
976
+ updatedAt: /* @__PURE__ */ new Date()
977
+ }).where(eq7(promoCodes.id, id));
978
+ }
979
+ async claimSlot(id, tx) {
980
+ const db = resolveDb(this.db, tx);
981
+ const claimed = await db.update(promoCodes).set({
982
+ redemptionsCount: sql`${promoCodes.redemptionsCount} + 1`,
983
+ updatedAt: /* @__PURE__ */ new Date()
984
+ }).where(and6(eq7(promoCodes.id, id), eq7(promoCodes.status, "ACTIVE"), isNull4(promoCodes.deletedAt), or(isNull4(promoCodes.maxRedemptions), lt3(promoCodes.redemptionsCount, promoCodes.maxRedemptions)))).returning({
985
+ id: promoCodes.id
986
+ });
987
+ return claimed.length === 1;
988
+ }
989
+ async markExhaustedIfFull(id, tx) {
990
+ const db = resolveDb(this.db, tx);
991
+ await db.update(promoCodes).set({
992
+ status: "EXHAUSTED",
993
+ updatedAt: /* @__PURE__ */ new Date()
994
+ }).where(and6(eq7(promoCodes.id, id), eq7(promoCodes.status, "ACTIVE"), isNotNull4(promoCodes.maxRedemptions), gte3(promoCodes.redemptionsCount, promoCodes.maxRedemptions)));
995
+ }
996
+ async releaseSlot(id, tx) {
997
+ const db = resolveDb(this.db, tx);
998
+ await db.update(promoCodes).set({
999
+ redemptionsCount: sql`GREATEST(${promoCodes.redemptionsCount} - 1, 0)`,
1000
+ status: sql`CASE WHEN ${promoCodes.status} = 'EXHAUSTED' THEN 'ACTIVE' ELSE ${promoCodes.status} END`,
1001
+ updatedAt: /* @__PURE__ */ new Date()
1002
+ }).where(eq7(promoCodes.id, id));
1003
+ }
1004
+ async expireDueCodes(now) {
1005
+ const expired = await this.db.update(promoCodes).set({
1006
+ status: "EXPIRED",
1007
+ updatedAt: /* @__PURE__ */ new Date()
1008
+ }).where(and6(inArray2(promoCodes.status, [
1009
+ "ACTIVE",
1010
+ "PAUSED"
1011
+ ]), lt3(promoCodes.validUntil, now))).returning({
1012
+ id: promoCodes.id
1013
+ });
1014
+ return expired.length;
1015
+ }
1016
+ };
1017
+ DrizzlePromoCodeRepository = _ts_decorate10([
1018
+ Injectable10(),
1019
+ _ts_param9(0, Inject9(DRIZZLE_DB_TOKEN)),
1020
+ _ts_metadata9("design:type", Function),
1021
+ _ts_metadata9("design:paramtypes", [
1022
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
1023
+ ])
1024
+ ], DrizzlePromoCodeRepository);
1025
+ function normalizeCode(code) {
1026
+ return code.trim().toUpperCase();
1027
+ }
1028
+ __name(normalizeCode, "normalizeCode");
1029
+ function toRecord2(row) {
1030
+ return {
1031
+ id: row.id,
1032
+ code: row.code,
1033
+ valueType: row.valueType,
1034
+ value: String(row.value),
1035
+ durationType: row.durationType,
1036
+ durationValue: row.durationValue,
1037
+ validFrom: row.validFrom,
1038
+ validUntil: row.validUntil,
1039
+ maxRedemptions: row.maxRedemptions,
1040
+ redemptionsCount: row.redemptionsCount,
1041
+ appliesToPlans: row.appliesToPlans ?? [],
1042
+ appliesToBilling: row.appliesToBilling ?? null,
1043
+ firstTimeCustomersOnly: row.firstTimeCustomersOnly,
1044
+ minimumPlanAmountGross: row.minimumPlanAmountGross === null ? null : String(row.minimumPlanAmountGross),
1045
+ allowZeroInvoice: row.allowZeroInvoice,
1046
+ status: row.status,
1047
+ description: row.description,
1048
+ campaignTag: row.campaignTag,
1049
+ revenueDeductionAccount: row.revenueDeductionAccount,
1050
+ createdById: row.createdById,
1051
+ createdAt: row.createdAt,
1052
+ updatedAt: row.updatedAt,
1053
+ deletedAt: row.deletedAt
1054
+ };
1055
+ }
1056
+ __name(toRecord2, "toRecord");
1057
+
1058
+ // src/drizzle-promo-code-validation-log.repository.ts
1059
+ import { randomUUID as randomUUID5 } from "node:crypto";
1060
+ import { Inject as Inject10, Injectable as Injectable11 } from "@nestjs/common";
1061
+ import { and as and7, eq as eq8 } from "drizzle-orm";
1062
+ function _ts_decorate11(decorators, target, key, desc4) {
1063
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1064
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1065
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1066
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1067
+ }
1068
+ __name(_ts_decorate11, "_ts_decorate");
1069
+ function _ts_metadata10(k, v) {
1070
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1071
+ }
1072
+ __name(_ts_metadata10, "_ts_metadata");
1073
+ function _ts_param10(paramIndex, decorator) {
1074
+ return function(target, key) {
1075
+ decorator(target, key, paramIndex);
1076
+ };
1077
+ }
1078
+ __name(_ts_param10, "_ts_param");
1079
+ var DrizzlePromoCodeValidationLogRepository = class {
1080
+ static {
1081
+ __name(this, "DrizzlePromoCodeValidationLogRepository");
1082
+ }
1083
+ db;
1084
+ constructor(db) {
1085
+ this.db = db;
1086
+ }
1087
+ async log(args) {
1088
+ await this.db.insert(promoCodeValidationLogs).values({
1089
+ id: randomUUID5(),
1090
+ promoCodeId: args.promoCodeId,
1091
+ codeAttempt: args.codeAttempt.trim().toUpperCase(),
1092
+ result: args.result,
1093
+ ipHash: args.ipHash ?? null,
1094
+ sessionId: args.sessionId ?? null
1095
+ });
1096
+ }
1097
+ async countValid(promoCodeId) {
1098
+ const rows = await this.db.select({
1099
+ id: promoCodeValidationLogs.id
1100
+ }).from(promoCodeValidationLogs).where(and7(eq8(promoCodeValidationLogs.promoCodeId, promoCodeId), eq8(promoCodeValidationLogs.result, "VALID")));
1101
+ return rows.length;
1102
+ }
1103
+ };
1104
+ DrizzlePromoCodeValidationLogRepository = _ts_decorate11([
1105
+ Injectable11(),
1106
+ _ts_param10(0, Inject10(DRIZZLE_DB_TOKEN)),
1107
+ _ts_metadata10("design:type", Function),
1108
+ _ts_metadata10("design:paramtypes", [
1109
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
1110
+ ])
1111
+ ], DrizzlePromoCodeValidationLogRepository);
1112
+
1113
+ // src/drizzle-promo-subscription-lookup.ts
1114
+ import { Inject as Inject11, Injectable as Injectable12 } from "@nestjs/common";
1115
+ import { eq as eq9 } from "drizzle-orm";
1116
+ function _ts_decorate12(decorators, target, key, desc4) {
1117
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1118
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1119
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1120
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1121
+ }
1122
+ __name(_ts_decorate12, "_ts_decorate");
1123
+ function _ts_metadata11(k, v) {
1124
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1125
+ }
1126
+ __name(_ts_metadata11, "_ts_metadata");
1127
+ function _ts_param11(paramIndex, decorator) {
1128
+ return function(target, key) {
1129
+ decorator(target, key, paramIndex);
1130
+ };
1131
+ }
1132
+ __name(_ts_param11, "_ts_param");
1133
+ var DrizzlePromoSubscriptionLookup = class {
1134
+ static {
1135
+ __name(this, "DrizzlePromoSubscriptionLookup");
1136
+ }
1137
+ db;
1138
+ constructor(db) {
1139
+ this.db = db;
1140
+ }
1141
+ async findById(subscriptionId, tx) {
1142
+ const db = resolveDb(this.db, tx);
1143
+ const rows = await db.select({
1144
+ id: subscriptions.id,
1145
+ tenantId: subscriptions.tenantId,
1146
+ plan: subscriptions.plan,
1147
+ billingCycle: subscriptions.billingCycle,
1148
+ startedAt: subscriptions.startedAt
1149
+ }).from(subscriptions).where(eq9(subscriptions.id, subscriptionId)).limit(1);
1150
+ const row = rows[0];
1151
+ if (!row) return null;
1152
+ return {
1153
+ id: row.id,
1154
+ tenantId: row.tenantId,
1155
+ plan: row.plan,
1156
+ billingCycle: row.billingCycle,
1157
+ startedAt: row.startedAt
1158
+ };
1159
+ }
1160
+ };
1161
+ DrizzlePromoSubscriptionLookup = _ts_decorate12([
1162
+ Injectable12(),
1163
+ _ts_param11(0, Inject11(DRIZZLE_DB_TOKEN)),
1164
+ _ts_metadata11("design:type", Function),
1165
+ _ts_metadata11("design:paramtypes", [
1166
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
1167
+ ])
1168
+ ], DrizzlePromoSubscriptionLookup);
1169
+
1170
+ // src/drizzle-subscription.repository.ts
1171
+ import { Inject as Inject12, Injectable as Injectable13 } from "@nestjs/common";
1172
+ import { eq as eq10, inArray as inArray3, or as or2 } from "drizzle-orm";
1173
+ function _ts_decorate13(decorators, target, key, desc4) {
1174
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1175
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1176
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1177
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1178
+ }
1179
+ __name(_ts_decorate13, "_ts_decorate");
1180
+ function _ts_metadata12(k, v) {
1181
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1182
+ }
1183
+ __name(_ts_metadata12, "_ts_metadata");
1184
+ function _ts_param12(paramIndex, decorator) {
1185
+ return function(target, key) {
1186
+ decorator(target, key, paramIndex);
1187
+ };
1188
+ }
1189
+ __name(_ts_param12, "_ts_param");
1190
+ var ACTIVE_STATUSES = [
1191
+ "ACTIVE",
1192
+ "TRIAL"
1193
+ ];
1194
+ var DrizzleSubscriptionRepository = class {
1195
+ static {
1196
+ __name(this, "DrizzleSubscriptionRepository");
1197
+ }
1198
+ db;
1199
+ constructor(db) {
1200
+ this.db = db;
1201
+ }
1202
+ async findByTenantId(tenantId) {
1203
+ return this.loadByTenantId(this.db, tenantId);
1204
+ }
1205
+ async findByTenantIdLocked(tenantId, tx) {
1206
+ const db = resolveDb(this.db, tx);
1207
+ await db.select({
1208
+ id: subscriptions.id
1209
+ }).from(subscriptions).where(eq10(subscriptions.tenantId, tenantId)).for("update");
1210
+ return this.loadByTenantId(db, tenantId);
1211
+ }
1212
+ async countByPlanVersionId(planVersionId) {
1213
+ const rows = await this.db.select({
1214
+ id: subscriptions.id
1215
+ }).from(subscriptions).where(or2(eq10(subscriptions.planVersionId, planVersionId), eq10(subscriptions.pendingPlanVersionId, planVersionId)));
1216
+ return rows.length;
1217
+ }
1218
+ async countActiveByPlanKey(_projectKey) {
1219
+ const rows = await this.db.select({
1220
+ plan: subscriptions.plan
1221
+ }).from(subscriptions).where(inArray3(subscriptions.status, ACTIVE_STATUSES));
1222
+ const counts = {};
1223
+ for (const row of rows) {
1224
+ counts[row.plan] = (counts[row.plan] ?? 0) + 1;
1225
+ }
1226
+ return counts;
1227
+ }
1228
+ async loadByTenantId(db, tenantId) {
1229
+ const rows = await db.select().from(subscriptions).where(eq10(subscriptions.tenantId, tenantId)).limit(1);
1230
+ const row = rows[0];
1231
+ if (!row) return null;
1232
+ return this.toRecord(db, row);
1233
+ }
1234
+ async toRecord(db, row) {
1235
+ if (!row.planVersionId) {
1236
+ throw new Error(`Subscription ${row.id} binds no planVersionId (businessType-only composition). The shipped @saasicat/adapter-drizzle SubscriptionRepository does not support BusinessType aggregation \u2014 provide a custom SubscriptionRepository adapter.`);
1237
+ }
1238
+ const versionRows = await db.select().from(planVersions).where(eq10(planVersions.id, row.planVersionId)).limit(1);
1239
+ const planVersion = versionRows[0];
1240
+ if (!planVersion) {
1241
+ throw new Error(`Subscription ${row.id} references missing PlanVersion ${row.planVersionId}.`);
1242
+ }
1243
+ return {
1244
+ id: row.id,
1245
+ tenantId: row.tenantId,
1246
+ plan: row.plan,
1247
+ status: row.status,
1248
+ isPilot: row.isPilot,
1249
+ trialEntitlementPlan: row.trialEntitlementPlan,
1250
+ pendingPlan: row.pendingPlan,
1251
+ pendingEffectiveAt: row.pendingEffectiveAt,
1252
+ customLimits: row.customLimits ?? null,
1253
+ planVersionId: row.planVersionId,
1254
+ planVersion: {
1255
+ planId: planVersion.planId,
1256
+ quotas: toQuotaMap(planVersion.quotas),
1257
+ features: toStringArray(planVersion.features)
1258
+ }
1259
+ };
1260
+ }
1261
+ };
1262
+ DrizzleSubscriptionRepository = _ts_decorate13([
1263
+ Injectable13(),
1264
+ _ts_param12(0, Inject12(DRIZZLE_DB_TOKEN)),
1265
+ _ts_metadata12("design:type", Function),
1266
+ _ts_metadata12("design:paramtypes", [
1267
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
1268
+ ])
1269
+ ], DrizzleSubscriptionRepository);
1270
+
1271
+ // src/drizzle-super-admin-bootstrap.adapter.ts
1272
+ import { randomUUID as randomUUID6 } from "node:crypto";
1273
+ import { Inject as Inject13, Injectable as Injectable14 } from "@nestjs/common";
1274
+ import { and as and8, count as count2, eq as eq11, isNull as isNull5 } from "drizzle-orm";
1275
+ import { PlatformUserExistsError } from "@saasicat/types";
1276
+ function _ts_decorate14(decorators, target, key, desc4) {
1277
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1278
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1279
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1280
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1281
+ }
1282
+ __name(_ts_decorate14, "_ts_decorate");
1283
+ function _ts_metadata13(k, v) {
1284
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1285
+ }
1286
+ __name(_ts_metadata13, "_ts_metadata");
1287
+ function _ts_param13(paramIndex, decorator) {
1288
+ return function(target, key) {
1289
+ decorator(target, key, paramIndex);
1290
+ };
1291
+ }
1292
+ __name(_ts_param13, "_ts_param");
1293
+ var PASSWORD_HASHER_TOKEN = /* @__PURE__ */ Symbol.for("saasicat/adapter-drizzle/PasswordHasher");
1294
+ var DrizzleSuperAdminBootstrapAdapter = class {
1295
+ static {
1296
+ __name(this, "DrizzleSuperAdminBootstrapAdapter");
1297
+ }
1298
+ db;
1299
+ passwordHasher;
1300
+ constructor(db, passwordHasher) {
1301
+ this.db = db;
1302
+ this.passwordHasher = passwordHasher;
1303
+ }
1304
+ async countSuperAdmins() {
1305
+ const rows = await this.db.select({
1306
+ value: count2()
1307
+ }).from(superAdminUsers).where(and8(eq11(superAdminUsers.isActive, true), isNull5(superAdminUsers.deletedAt)));
1308
+ return rows[0]?.value ?? 0;
1309
+ }
1310
+ async createSuperAdmin(input) {
1311
+ const email = input.email.trim().toLowerCase();
1312
+ const existing = await this.db.select().from(superAdminUsers).where(eq11(superAdminUsers.email, email)).limit(1);
1313
+ if (existing[0]) {
1314
+ throw new PlatformUserExistsError(email, existing[0].platformRole);
1315
+ }
1316
+ const rows = await this.db.insert(superAdminUsers).values({
1317
+ id: randomUUID6(),
1318
+ email,
1319
+ passwordHash: await this.passwordHasher.hash(input.password),
1320
+ firstName: input.firstName ?? null,
1321
+ lastName: input.lastName ?? null,
1322
+ updatedAt: /* @__PURE__ */ new Date()
1323
+ }).returning();
1324
+ const row = rows[0];
1325
+ return {
1326
+ id: row.id,
1327
+ email: row.email,
1328
+ firstName: row.firstName ?? void 0,
1329
+ lastName: row.lastName ?? void 0,
1330
+ platformRole: row.platformRole,
1331
+ isActive: row.isActive,
1332
+ lastLoginAt: null,
1333
+ deletedAt: null
1334
+ };
1335
+ }
1336
+ };
1337
+ DrizzleSuperAdminBootstrapAdapter = _ts_decorate14([
1338
+ Injectable14(),
1339
+ _ts_param13(0, Inject13(DRIZZLE_DB_TOKEN)),
1340
+ _ts_param13(1, Inject13(PASSWORD_HASHER_TOKEN)),
1341
+ _ts_metadata13("design:type", Function),
1342
+ _ts_metadata13("design:paramtypes", [
1343
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient,
1344
+ typeof PasswordHasher === "undefined" ? Object : PasswordHasher
1345
+ ])
1346
+ ], DrizzleSuperAdminBootstrapAdapter);
1347
+
1348
+ // src/drizzle-transaction-runner.ts
1349
+ import { Inject as Inject14, Injectable as Injectable15 } from "@nestjs/common";
1350
+ function _ts_decorate15(decorators, target, key, desc4) {
1351
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1352
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1353
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1354
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1355
+ }
1356
+ __name(_ts_decorate15, "_ts_decorate");
1357
+ function _ts_metadata14(k, v) {
1358
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1359
+ }
1360
+ __name(_ts_metadata14, "_ts_metadata");
1361
+ function _ts_param14(paramIndex, decorator) {
1362
+ return function(target, key) {
1363
+ decorator(target, key, paramIndex);
1364
+ };
1365
+ }
1366
+ __name(_ts_param14, "_ts_param");
1367
+ var DrizzleTransactionRunner = class {
1368
+ static {
1369
+ __name(this, "DrizzleTransactionRunner");
1370
+ }
1371
+ db;
1372
+ constructor(db) {
1373
+ this.db = db;
1374
+ }
1375
+ async run(fn) {
1376
+ return this.db.transaction((tx) => fn(tx));
1377
+ }
1378
+ };
1379
+ DrizzleTransactionRunner = _ts_decorate15([
1380
+ Injectable15(),
1381
+ _ts_param14(0, Inject14(DRIZZLE_DB_TOKEN)),
1382
+ _ts_metadata14("design:type", Function),
1383
+ _ts_metadata14("design:paramtypes", [
1384
+ typeof DrizzleClient === "undefined" ? Object : DrizzleClient
1385
+ ])
1386
+ ], DrizzleTransactionRunner);
1387
+
1388
+ // src/zero-promo-revenue-aggregator.ts
1389
+ import { Injectable as Injectable16 } from "@nestjs/common";
1390
+ function _ts_decorate16(decorators, target, key, desc4) {
1391
+ var c = arguments.length, r = c < 3 ? target : desc4 === null ? desc4 = Object.getOwnPropertyDescriptor(target, key) : desc4, d;
1392
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc4);
1393
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1394
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1395
+ }
1396
+ __name(_ts_decorate16, "_ts_decorate");
1397
+ var ZeroPromoRevenueDeductionAggregator = class {
1398
+ static {
1399
+ __name(this, "ZeroPromoRevenueDeductionAggregator");
1400
+ }
1401
+ async sumGrossForPromoCode(_promoCodeId) {
1402
+ return "0.00";
1403
+ }
1404
+ };
1405
+ ZeroPromoRevenueDeductionAggregator = _ts_decorate16([
1406
+ Injectable16()
1407
+ ], ZeroPromoRevenueDeductionAggregator);
1408
+
1409
+ // src/drizzle-persistence.ts
1410
+ function drizzlePersistence(options) {
1411
+ const { db } = options;
1412
+ const provide = /* @__PURE__ */ __name((build) => isInjectionToken(db) ? {
1413
+ useFactory: /* @__PURE__ */ __name((client) => build(client), "useFactory"),
1414
+ inject: [
1415
+ db
1416
+ ]
1417
+ } : build(db), "provide");
1418
+ return {
1419
+ capabilities: {
1420
+ transactions: true,
1421
+ pessimisticLocking: true,
1422
+ rowLevelSecurity: options.rlsIntegration ?? false,
1423
+ advisoryLocks: false
1424
+ },
1425
+ core: {
1426
+ mfa: provide((client) => new DrizzleMfaAdapter(client)),
1427
+ audit: provide((client) => new DrizzleAuditAdapter(client)),
1428
+ rlsBypass: new AsyncLocalRlsBypassAdapter(),
1429
+ transactionRunner: provide((client) => new DrizzleTransactionRunner(client)),
1430
+ auditQuery: provide((client) => new DrizzleAuditQueryAdapter(client)),
1431
+ auditStats: provide((client) => new DrizzleAuditStatsAdapter(client)),
1432
+ superAdminProvisioning: buildProvisioning(db, options.passwordHasher)
1433
+ },
1434
+ entitlement: {
1435
+ subscriptionRepository: provide((client) => new DrizzleSubscriptionRepository(client)),
1436
+ planVersionRepository: provide((client) => new DrizzlePlanVersionRepository(client))
1437
+ },
1438
+ promo: {
1439
+ promoCodeRepository: provide((client) => new DrizzlePromoCodeRepository(client)),
1440
+ redemptionRepository: provide((client) => new DrizzlePromoCodeRedemptionRepository(client)),
1441
+ validationLogRepository: provide((client) => new DrizzlePromoCodeValidationLogRepository(client)),
1442
+ subscriptionLookup: provide((client) => new DrizzlePromoSubscriptionLookup(client)),
1443
+ revenueAggregator: new ZeroPromoRevenueDeductionAggregator()
1444
+ },
1445
+ planCatalogReadSink: provide((client) => new DrizzlePlanCatalogReadSink(client)),
1446
+ planCatalogImportSink: provide((client) => new DrizzlePlanCatalogImportSink(client))
1447
+ };
1448
+ }
1449
+ __name(drizzlePersistence, "drizzlePersistence");
1450
+ function isInjectionToken(value) {
1451
+ return typeof value === "function" || typeof value === "symbol" || typeof value === "string";
1452
+ }
1453
+ __name(isInjectionToken, "isInjectionToken");
1454
+ function buildProvisioning(db, hasher) {
1455
+ if (hasher === void 0) return void 0;
1456
+ const dbIsToken = isInjectionToken(db);
1457
+ const hasherIsToken = isInjectionToken(hasher);
1458
+ if (dbIsToken && hasherIsToken) {
1459
+ return {
1460
+ useFactory: /* @__PURE__ */ __name((client, h) => new DrizzleSuperAdminBootstrapAdapter(client, h), "useFactory"),
1461
+ inject: [
1462
+ db,
1463
+ hasher
1464
+ ]
1465
+ };
1466
+ }
1467
+ if (dbIsToken) {
1468
+ return {
1469
+ useFactory: /* @__PURE__ */ __name((client) => new DrizzleSuperAdminBootstrapAdapter(client, hasher), "useFactory"),
1470
+ inject: [
1471
+ db
1472
+ ]
1473
+ };
1474
+ }
1475
+ if (hasherIsToken) {
1476
+ return {
1477
+ useFactory: /* @__PURE__ */ __name((h) => new DrizzleSuperAdminBootstrapAdapter(db, h), "useFactory"),
1478
+ inject: [
1479
+ hasher
1480
+ ]
1481
+ };
1482
+ }
1483
+ return new DrizzleSuperAdminBootstrapAdapter(db, hasher);
1484
+ }
1485
+ __name(buildProvisioning, "buildProvisioning");
1486
+ export {
1487
+ AsyncLocalRlsBypassAdapter,
1488
+ DRIZZLE_DB_TOKEN,
1489
+ DrizzleAuditAdapter,
1490
+ DrizzleAuditQueryAdapter,
1491
+ DrizzleAuditStatsAdapter,
1492
+ DrizzleMfaAdapter,
1493
+ DrizzlePlanCatalogImportSink,
1494
+ DrizzlePlanCatalogReadSink,
1495
+ DrizzlePlanVersionRepository,
1496
+ DrizzlePromoCodeRedemptionRepository,
1497
+ DrizzlePromoCodeRepository,
1498
+ DrizzlePromoCodeValidationLogRepository,
1499
+ DrizzlePromoSubscriptionLookup,
1500
+ DrizzleSubscriptionRepository,
1501
+ DrizzleSuperAdminBootstrapAdapter,
1502
+ DrizzleTransactionRunner,
1503
+ PASSWORD_HASHER_TOKEN,
1504
+ ZeroPromoRevenueDeductionAggregator,
1505
+ buildActorTag,
1506
+ drizzlePersistence,
1507
+ schema_exports as saasicatSchema
1508
+ };