@canton-network/core-wallet-store-sql 1.8.0 → 1.10.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 CHANGED
@@ -1,962 +1,838 @@
1
- import { assertConnected, authSchema } from '@canton-network/core-wallet-auth';
2
- import { Kysely, CamelCasePlugin, SqliteDialect, PostgresDialect } from 'kysely';
3
- import Database from 'better-sqlite3';
4
- import { PartyLevelRight, UserLevelRight } from '@canton-network/core-wallet-store';
5
- import pg from 'pg';
6
- import { Umzug } from 'umzug';
7
- import { Command } from 'commander';
8
- import { pino } from 'pino';
9
-
10
- var __defProp = Object.defineProperty;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
13
- var toIdp = (table) => {
14
- switch (table.type) {
15
- case "oauth": {
16
- if (!table.configUrl) {
17
- throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
18
- }
19
- return {
20
- id: table.id,
21
- type: table.type,
22
- issuer: table.issuer,
23
- configUrl: table.configUrl
24
- };
25
- }
26
- case "self_signed":
27
- return {
28
- id: table.id,
29
- type: table.type,
30
- issuer: table.issuer
31
- };
32
- }
1
+ import { assertConnected, authSchema } from "@canton-network/core-wallet-auth";
2
+ import { CamelCasePlugin, Kysely, PostgresDialect, SqliteDialect, sql } from "kysely";
3
+ import Database from "better-sqlite3";
4
+ import { PartyLevelRight, UserLevelRight } from "@canton-network/core-wallet-store";
5
+ import pg from "pg";
6
+ import { Umzug } from "umzug";
7
+ import { Command } from "commander";
8
+ import { pino } from "pino";
9
+ //#region src/schema.ts
10
+ const toIdp = (table) => {
11
+ switch (table.type) {
12
+ case "oauth":
13
+ if (!table.configUrl) throw new Error(`Missing configUrl for oauth IdP: ${table.id}`);
14
+ return {
15
+ id: table.id,
16
+ type: table.type,
17
+ issuer: table.issuer,
18
+ configUrl: table.configUrl
19
+ };
20
+ case "self_signed": return {
21
+ id: table.id,
22
+ type: table.type,
23
+ issuer: table.issuer
24
+ };
25
+ }
26
+ };
27
+ const fromIdp = (idp) => {
28
+ switch (idp.type) {
29
+ case "oauth": return {
30
+ id: idp.id,
31
+ type: idp.type,
32
+ issuer: idp.issuer,
33
+ configUrl: idp.configUrl
34
+ };
35
+ case "self_signed": return {
36
+ id: idp.id,
37
+ type: idp.type,
38
+ issuer: idp.issuer,
39
+ configUrl: void 0
40
+ };
41
+ }
33
42
  };
34
- var fromIdp = (idp) => {
35
- switch (idp.type) {
36
- case "oauth":
37
- return {
38
- id: idp.id,
39
- type: idp.type,
40
- issuer: idp.issuer,
41
- configUrl: idp.configUrl
42
- };
43
- case "self_signed":
44
- return {
45
- id: idp.id,
46
- type: idp.type,
47
- issuer: idp.issuer,
48
- configUrl: void 0
49
- };
50
- }
43
+ const toNetwork = (table) => {
44
+ return {
45
+ name: table.name,
46
+ id: table.id,
47
+ synchronizerId: table.synchronizerId ?? void 0,
48
+ identityProviderId: table.identityProviderId,
49
+ description: table.description,
50
+ ledgerApi: { baseUrl: table.ledgerApiBaseUrl },
51
+ auth: authSchema.parse(typeof table.auth === "string" ? JSON.parse(table.auth) : table.auth),
52
+ adminAuth: table.adminAuth ? authSchema.parse(typeof table.adminAuth === "string" ? JSON.parse(table.adminAuth) : table.adminAuth) : void 0,
53
+ serviceAccountAuth: table.serviceAccountAuth ? authSchema.parse(typeof table.serviceAccountAuth === "string" ? JSON.parse(table.serviceAccountAuth) : table.serviceAccountAuth) : void 0
54
+ };
51
55
  };
52
- var toNetwork = (table) => {
53
- return {
54
- name: table.name,
55
- id: table.id,
56
- synchronizerId: table.synchronizerId ?? void 0,
57
- identityProviderId: table.identityProviderId,
58
- description: table.description,
59
- ledgerApi: {
60
- baseUrl: table.ledgerApiBaseUrl
61
- },
62
- auth: authSchema.parse(
63
- typeof table.auth === "string" ? JSON.parse(table.auth) : table.auth
64
- ),
65
- adminAuth: table.adminAuth ? authSchema.parse(
66
- typeof table.adminAuth === "string" ? JSON.parse(table.adminAuth) : table.adminAuth
67
- ) : void 0,
68
- serviceAccountAuth: table.serviceAccountAuth ? authSchema.parse(
69
- typeof table.serviceAccountAuth === "string" ? JSON.parse(table.serviceAccountAuth) : table.serviceAccountAuth
70
- ) : void 0
71
- };
56
+ const fromNetwork = (network, userId) => {
57
+ return {
58
+ name: network.name,
59
+ id: network.id,
60
+ synchronizerId: network.synchronizerId ?? null,
61
+ description: network.description,
62
+ ledgerApiBaseUrl: network.ledgerApi.baseUrl,
63
+ userId,
64
+ identityProviderId: network.identityProviderId,
65
+ auth: JSON.stringify(network.auth),
66
+ adminAuth: network.adminAuth ? JSON.stringify(network.adminAuth) : void 0,
67
+ serviceAccountAuth: network.serviceAccountAuth ? JSON.stringify(network.serviceAccountAuth) : void 0
68
+ };
72
69
  };
73
- var fromNetwork = (network, userId) => {
74
- return {
75
- name: network.name,
76
- id: network.id,
77
- synchronizerId: network.synchronizerId ?? null,
78
- description: network.description,
79
- ledgerApiBaseUrl: network.ledgerApi.baseUrl,
80
- userId,
81
- identityProviderId: network.identityProviderId,
82
- auth: JSON.stringify(network.auth),
83
- adminAuth: network.adminAuth ? JSON.stringify(network.adminAuth) : void 0,
84
- serviceAccountAuth: network.serviceAccountAuth ? JSON.stringify(network.serviceAccountAuth) : void 0
85
- };
70
+ const toSession = (table) => {
71
+ return {
72
+ id: table.id,
73
+ network: table.network,
74
+ origin: table.origin,
75
+ accessToken: table.accessToken,
76
+ userId: table.userId
77
+ };
86
78
  };
87
- var fromWallet = (wallet, userId) => {
88
- const { externalTxId, topologyTransactions, rights, ...rest } = wallet;
89
- return {
90
- ...rest,
91
- primary: wallet.primary ? 1 : 0,
92
- userId,
93
- disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
94
- reason: wallet.reason ?? null,
95
- externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
96
- topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
97
- };
79
+ const fromWallet = (wallet, userId) => {
80
+ const { externalTxId, topologyTransactions, rights, ...rest } = wallet;
81
+ return {
82
+ ...rest,
83
+ primary: wallet.primary ? 1 : 0,
84
+ userId,
85
+ disabled: wallet.disabled !== void 0 && wallet.disabled ? 1 : 0,
86
+ reason: wallet.reason ?? null,
87
+ externalTxId: externalTxId && externalTxId !== "" ? externalTxId : null,
88
+ topologyTransactions: topologyTransactions && topologyTransactions !== "" ? topologyTransactions : null
89
+ };
98
90
  };
99
- var toWalletUpdateProperties = (params) => {
100
- const {
101
- status,
102
- externalTxId,
103
- topologyTransactions,
104
- disabled,
105
- reason,
106
- primary
107
- } = params;
108
- return {
109
- ...status !== void 0 && { status },
110
- ...externalTxId !== void 0 && { externalTxId },
111
- ...topologyTransactions !== void 0 && { topologyTransactions },
112
- ...primary !== void 0 && { primary: primary ? 1 : 0 },
113
- ...disabled !== void 0 && { disabled: disabled ? 1 : 0 },
114
- ...reason !== void 0 && { reason }
115
- };
91
+ const toWalletUpdateProperties = (params) => {
92
+ const { status, externalTxId, topologyTransactions, disabled, reason, primary } = params;
93
+ return {
94
+ ...status !== void 0 && { status },
95
+ ...externalTxId !== void 0 && { externalTxId },
96
+ ...topologyTransactions !== void 0 && { topologyTransactions },
97
+ ...primary !== void 0 && { primary: primary ? 1 : 0 },
98
+ ...disabled !== void 0 && { disabled: disabled ? 1 : 0 },
99
+ ...reason !== void 0 && { reason }
100
+ };
116
101
  };
117
- var toWalletStatus = (status) => {
118
- if (status === "allocated") return "allocated";
119
- if (status === "removed") return "removed";
120
- return "initialized";
102
+ const toWalletStatus = (status) => {
103
+ if (status === "allocated") return "allocated";
104
+ if (status === "removed") return "removed";
105
+ return "initialized";
121
106
  };
122
- var toWallet = (table) => {
123
- return {
124
- primary: Boolean(table.primary),
125
- status: toWalletStatus(table.status),
126
- partyId: table.partyId,
127
- hint: table.hint,
128
- publicKey: table.publicKey,
129
- namespace: table.namespace,
130
- networkId: table.networkId,
131
- signingProviderId: table.signingProviderId,
132
- disabled: table.disabled === 1,
133
- ...table.externalTxId !== null && {
134
- externalTxId: table.externalTxId
135
- },
136
- ...table.topologyTransactions !== null && {
137
- topologyTransactions: table.topologyTransactions
138
- },
139
- ...table.reason !== null && {
140
- reason: table.reason
141
- },
142
- rights: []
143
- };
107
+ const toWallet = (table) => {
108
+ return {
109
+ primary: Boolean(table.primary),
110
+ status: toWalletStatus(table.status),
111
+ partyId: table.partyId,
112
+ hint: table.hint,
113
+ publicKey: table.publicKey,
114
+ namespace: table.namespace,
115
+ networkId: table.networkId,
116
+ signingProviderId: table.signingProviderId,
117
+ disabled: table.disabled === 1,
118
+ ...table.externalTxId !== null && { externalTxId: table.externalTxId },
119
+ ...table.topologyTransactions !== null && { topologyTransactions: table.topologyTransactions },
120
+ ...table.reason !== null && { reason: table.reason },
121
+ rights: []
122
+ };
144
123
  };
145
- var fromPartyRight = (right) => {
146
- if (Object.values(PartyLevelRight).includes(right)) {
147
- return right;
148
- }
149
- return void 0;
124
+ const fromPartyRight = (right) => {
125
+ if (Object.values(PartyLevelRight).includes(right)) return right;
150
126
  };
151
- var fromUserRight = (right) => {
152
- if (Object.values(UserLevelRight).includes(right)) {
153
- return right;
154
- }
155
- return void 0;
127
+ const fromUserRight = (right) => {
128
+ if (Object.values(UserLevelRight).includes(right)) return right;
156
129
  };
157
- var fromTransaction = (transaction, userId, networkId) => {
158
- return {
159
- ...transaction,
160
- networkId,
161
- payload: transaction.payload ? JSON.stringify(transaction.payload) : void 0,
162
- origin: transaction.origin || null,
163
- userId,
164
- createdAt: transaction.createdAt?.toISOString() || null,
165
- signedAt: transaction.signedAt?.toISOString() || null,
166
- externalTxId: transaction.externalTxId ?? null
167
- };
130
+ const fromTransaction = (transaction, userId, networkId) => {
131
+ return {
132
+ ...transaction,
133
+ networkId,
134
+ payload: transaction.payload ? JSON.stringify(transaction.payload) : void 0,
135
+ origin: transaction.origin || null,
136
+ userId,
137
+ createdAt: transaction.createdAt?.toISOString() || null,
138
+ signedAt: transaction.signedAt?.toISOString() || null,
139
+ externalTxId: transaction.externalTxId ?? null
140
+ };
168
141
  };
169
- var toTransaction = (table) => {
170
- const result = {
171
- id: table.id,
172
- commandId: table.commandId,
173
- status: table.status,
174
- preparedTransaction: table.preparedTransaction,
175
- preparedTransactionHash: table.preparedTransactionHash,
176
- payload: table.payload ? JSON.parse(table.payload) : void 0,
177
- origin: table.origin || null
178
- };
179
- if (table.createdAt) {
180
- result.createdAt = new Date(table.createdAt);
181
- }
182
- if (table.signedAt) {
183
- result.signedAt = new Date(table.signedAt);
184
- }
185
- if (table.externalTxId) {
186
- result.externalTxId = table.externalTxId;
187
- }
188
- return result;
142
+ const toTransaction = (table) => {
143
+ const result = {
144
+ id: table.id,
145
+ commandId: table.commandId,
146
+ status: table.status,
147
+ preparedTransaction: table.preparedTransaction,
148
+ preparedTransactionHash: table.preparedTransactionHash,
149
+ payload: table.payload ? JSON.parse(table.payload) : void 0,
150
+ origin: table.origin || null,
151
+ userId: table.userId,
152
+ networkId: table.networkId
153
+ };
154
+ if (table.createdAt) result.createdAt = new Date(table.createdAt);
155
+ if (table.signedAt) result.signedAt = new Date(table.signedAt);
156
+ if (table.externalTxId) result.externalTxId = table.externalTxId;
157
+ return result;
189
158
  };
190
- var fromMessageRaw = (message, userId, networkId) => {
191
- if (message.userId !== userId) {
192
- throw new Error(
193
- `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`
194
- );
195
- }
196
- return {
197
- id: message.id,
198
- status: message.status,
199
- userId: message.userId,
200
- partyId: message.partyId,
201
- publicKey: message.publicKey,
202
- message: message.message,
203
- origin: message.origin || null,
204
- networkId,
205
- createdAt: message.createdAt.toISOString(),
206
- signedAt: message.signedAt?.toISOString() || null,
207
- signature: message.signature ?? null
208
- };
159
+ const fromMessageRaw = (message, userId, networkId) => {
160
+ if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
161
+ return {
162
+ id: message.id,
163
+ status: message.status,
164
+ userId: message.userId,
165
+ partyId: message.partyId,
166
+ publicKey: message.publicKey,
167
+ message: message.message,
168
+ origin: message.origin || null,
169
+ networkId,
170
+ createdAt: message.createdAt.toISOString(),
171
+ signedAt: message.signedAt?.toISOString() || null,
172
+ signature: message.signature ?? null
173
+ };
209
174
  };
210
- var toMessageRaw = (table) => {
211
- const result = {
212
- id: table.id,
213
- status: table.status,
214
- userId: table.userId,
215
- partyId: table.partyId,
216
- publicKey: table.publicKey,
217
- message: table.message,
218
- origin: table.origin || null,
219
- createdAt: new Date(table.createdAt)
220
- };
221
- if (table.signedAt) {
222
- result.signedAt = new Date(table.signedAt);
223
- }
224
- if (table.signature) {
225
- result.signature = table.signature;
226
- }
227
- return result;
175
+ const toMessageRaw = (table) => {
176
+ const result = {
177
+ id: table.id,
178
+ status: table.status,
179
+ userId: table.userId,
180
+ partyId: table.partyId,
181
+ publicKey: table.publicKey,
182
+ message: table.message,
183
+ origin: table.origin || null,
184
+ createdAt: new Date(table.createdAt)
185
+ };
186
+ if (table.signedAt) result.signedAt = new Date(table.signedAt);
187
+ if (table.signature) result.signature = table.signature;
188
+ return result;
228
189
  };
229
- var fromApiKey = (table) => {
230
- return {
231
- id: table.id,
232
- digest: table.digest,
233
- name: table.name,
234
- userId: table.userId,
235
- email: table.email,
236
- networkId: table.networkId,
237
- createdAt: new Date(table.createdAt),
238
- lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : void 0
239
- };
190
+ const fromApiKey = (table) => {
191
+ return {
192
+ id: table.id,
193
+ digest: table.digest,
194
+ name: table.name,
195
+ userId: table.userId,
196
+ email: table.email,
197
+ networkId: table.networkId,
198
+ createdAt: new Date(table.createdAt),
199
+ lastUsedAt: table.lastUsedAt ? new Date(table.lastUsedAt) : void 0
200
+ };
240
201
  };
241
- var toApiKey = (apiKey) => {
242
- return {
243
- id: apiKey.id,
244
- digest: apiKey.digest,
245
- name: apiKey.name,
246
- userId: apiKey.userId,
247
- email: apiKey.email,
248
- networkId: apiKey.networkId,
249
- createdAt: apiKey.createdAt.toISOString(),
250
- lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
251
- };
202
+ const toApiKey = (apiKey) => {
203
+ return {
204
+ id: apiKey.id,
205
+ digest: apiKey.digest,
206
+ name: apiKey.name,
207
+ userId: apiKey.userId,
208
+ email: apiKey.email,
209
+ networkId: apiKey.networkId,
210
+ createdAt: apiKey.createdAt.toISOString(),
211
+ lastUsedAt: apiKey.lastUsedAt ? apiKey.lastUsedAt.toISOString() : null
212
+ };
252
213
  };
253
- var StoreSql = class _StoreSql {
254
- constructor(db, logger2, authContext) {
255
- this.db = db;
256
- this.logger = logger2;
257
- __publicField(this, "authContext");
258
- this.logger = logger2.child({ component: "StoreSql" });
259
- this.authContext = authContext;
260
- }
261
- withAuthContext(context) {
262
- return new _StoreSql(this.db, this.logger, context);
263
- }
264
- assertConnected() {
265
- return assertConnected(this.authContext).userId;
266
- }
267
- // Wallet methods
268
- async getAllWallets(filter = {}) {
269
- const userId = this.assertConnected();
270
- const { networkIds, signingProviderIds } = filter;
271
- const networkIdSet = networkIds ? new Set(networkIds) : null;
272
- const signingProviderIdSet = signingProviderIds ? new Set(signingProviderIds) : null;
273
- const wallets = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).execute();
274
- const userPartyRights = await this.db.selectFrom("userPartyRights").selectAll().where("userId", "=", userId).execute();
275
- const rightsByWallet = /* @__PURE__ */ new Map();
276
- for (const row of userPartyRights) {
277
- const right = fromPartyRight(row.right);
278
- if (!right) continue;
279
- const key = `${row.partyId}:${row.networkId}`;
280
- const existing = rightsByWallet.get(key) ?? [];
281
- rightsByWallet.set(key, [...existing, right]);
282
- }
283
- return wallets.filter((wallet) => {
284
- const matchedNetworkIds = networkIdSet ? networkIdSet.has(wallet.networkId) : true;
285
- const matchedSigningProviderIds = signingProviderIdSet ? signingProviderIdSet.has(wallet.signingProviderId) : true;
286
- return matchedNetworkIds && matchedSigningProviderIds;
287
- }).map((table) => {
288
- const wallet = toWallet(table);
289
- const rights = rightsByWallet.get(
290
- `${table.partyId}:${table.networkId}`
291
- );
292
- return {
293
- ...wallet,
294
- rights: rights ?? []
295
- };
296
- });
297
- }
298
- async getWallets(filter = {}) {
299
- const network = await this.getCurrentNetwork();
300
- return this.getAllWallets({
301
- ...filter,
302
- networkIds: [network.id]
303
- });
304
- }
305
- async getPrimaryWallet() {
306
- const wallets = await this.getWallets();
307
- return wallets.find((w) => w.primary === true);
308
- }
309
- async setPrimaryWallet(partyId) {
310
- const network = await this.getCurrentNetwork();
311
- const userId = this.assertConnected();
312
- const wallets = await this.getWallets();
313
- if (!wallets.some((w) => w.partyId === partyId)) {
314
- throw new Error(
315
- `Wallet with partyId "${partyId}" not found in network "${network.id}"`
316
- );
317
- }
318
- const primary = wallets.find((w) => w.primary === true);
319
- await this.db.transaction().execute(async (trx) => {
320
- if (primary) {
321
- await trx.updateTable("wallets").set({ primary: 0 }).where(
322
- (eb) => eb.and([
323
- eb("partyId", "=", primary.partyId),
324
- eb("networkId", "=", network.id),
325
- eb("userId", "=", userId)
326
- ])
327
- ).execute();
328
- }
329
- await trx.updateTable("wallets").set({ primary: 1 }).where(
330
- (eb) => eb.and([
331
- eb("partyId", "=", partyId),
332
- eb("networkId", "=", network.id),
333
- eb("userId", "=", userId)
334
- ])
335
- ).execute();
336
- });
337
- }
338
- async addWallet(wallet) {
339
- this.logger.info("Adding wallet");
340
- const userId = this.assertConnected();
341
- const wallets = await this.getWallets();
342
- if (wallets.some(
343
- (w) => w.partyId === wallet.partyId && w.networkId === wallet.networkId
344
- )) {
345
- throw new Error(
346
- `Wallet with partyId "${wallet.partyId}" networkId "${wallet.networkId}" userId "${userId}" already exists`
347
- );
348
- }
349
- if (!wallet.disabled && wallet.status === "allocated" && !wallets.some((wallet2) => wallet2.primary)) {
350
- wallet.primary = true;
351
- }
352
- await this.db.transaction().execute(async (trx) => {
353
- if (wallet.primary) {
354
- await trx.updateTable("wallets").set({ primary: 0 }).where(
355
- (eb) => eb.and([
356
- eb("primary", "=", 1),
357
- eb("networkId", "=", wallet.networkId),
358
- eb("userId", "=", userId)
359
- ])
360
- ).execute();
361
- }
362
- await trx.insertInto("wallets").values(fromWallet(wallet, userId)).execute();
363
- if (wallet.rights && wallet.rights.length > 0) {
364
- await trx.insertInto("userPartyRights").values(
365
- wallet.rights.map((right) => ({
366
- userId,
367
- networkId: wallet.networkId,
368
- partyId: wallet.partyId,
369
- right
370
- }))
371
- ).execute();
372
- }
373
- });
374
- }
375
- async updateWallet(params) {
376
- const { partyId, networkId, rights } = params;
377
- this.logger.info("Updating wallet");
378
- const userId = this.assertConnected();
379
- const updates = toWalletUpdateProperties(params);
380
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
381
- if (Object.keys(updates).length === 0 && rights === void 0) return;
382
- await this.db.transaction().execute(async (trx) => {
383
- if (Object.keys(updates).length > 0) {
384
- await trx.updateTable("wallets").set(updates).where(
385
- (eb) => eb.and([
386
- eb("partyId", "=", partyId),
387
- eb("networkId", "=", targetNetworkId),
388
- eb("userId", "=", userId)
389
- ])
390
- ).execute();
391
- }
392
- if (rights !== void 0) {
393
- await trx.deleteFrom("userPartyRights").where(
394
- (eb) => eb.and([
395
- eb("partyId", "=", partyId),
396
- eb("networkId", "=", targetNetworkId),
397
- eb("userId", "=", userId)
398
- ])
399
- ).execute();
400
- if (rights.length > 0) {
401
- await trx.insertInto("userPartyRights").values(
402
- rights.map((right) => ({
403
- userId,
404
- networkId: targetNetworkId,
405
- partyId,
406
- right
407
- }))
408
- ).execute();
409
- }
410
- }
411
- });
412
- }
413
- async removeWallet(partyId) {
414
- this.logger.info("Removing wallet");
415
- const userId = this.assertConnected();
416
- const network = await this.getCurrentNetwork();
417
- await this.db.transaction().execute(async (trx) => {
418
- await trx.deleteFrom("wallets").where(
419
- (eb) => eb.and([
420
- eb("partyId", "=", partyId),
421
- eb("networkId", "=", network.id),
422
- eb("userId", "=", userId)
423
- ])
424
- ).execute();
425
- });
426
- }
427
- async getUserRights(networkId) {
428
- const userId = this.assertConnected();
429
- const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
430
- const rows = await this.db.selectFrom("userRights").selectAll().where(
431
- (eb) => eb.and([
432
- eb("userId", "=", userId),
433
- eb("networkId", "=", targetNetworkId)
434
- ])
435
- ).execute();
436
- return rows.map((row) => fromUserRight(row.right)).filter((right) => right !== void 0);
437
- }
438
- async setUserRights(networkId, rights) {
439
- const userId = this.assertConnected();
440
- await this.db.transaction().execute(async (trx) => {
441
- await trx.deleteFrom("userRights").where(
442
- (eb) => eb.and([
443
- eb("userId", "=", userId),
444
- eb("networkId", "=", networkId)
445
- ])
446
- ).execute();
447
- if (rights.length > 0) {
448
- await trx.insertInto("userRights").values(
449
- rights.map((right) => ({
450
- userId,
451
- networkId,
452
- right
453
- }))
454
- ).execute();
455
- }
456
- });
457
- }
458
- // Session methods
459
- async getSession() {
460
- const userId = this.assertConnected();
461
- const sessions = await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).executeTakeFirst();
462
- return sessions;
463
- }
464
- async setSession(session) {
465
- const userId = this.assertConnected();
466
- await this.db.transaction().execute(async (trx) => {
467
- const deleted = await trx.deleteFrom("sessions").where("userId", "=", userId).execute();
468
- this.logger.debug(deleted, "Deleted old session");
469
- const inserted = await trx.insertInto("sessions").values({ ...session, userId }).execute();
470
- this.logger.debug(inserted, "Inserted new session");
471
- });
472
- }
473
- async removeSession() {
474
- const userId = this.assertConnected();
475
- await this.db.deleteFrom("sessions").where("userId", "=", userId).execute();
476
- }
477
- // IDP methods
478
- async getIdp(idpId) {
479
- this.assertConnected();
480
- const idps = await this.listIdps();
481
- if (!idps) throw new Error("No IDPs available");
482
- const idp = idps.find((n) => n.id === idpId);
483
- if (!idp) throw new Error(`IDP "${idpId}" not found`);
484
- return idp;
485
- }
486
- async listIdps() {
487
- const query = this.db.selectFrom("idps").selectAll();
488
- const idps = await query.execute();
489
- return idps.map((table) => toIdp(table));
490
- }
491
- async updateIdp(idp) {
492
- await this.db.transaction().execute(async (trx) => {
493
- const idpEntry = fromIdp(idp);
494
- this.logger.info(idpEntry, "Updating idp table");
495
- await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
496
- });
497
- }
498
- async addIdp(idp) {
499
- await this.db.transaction().execute(async (trx) => {
500
- const idpAlreadyExists = await trx.selectFrom("idps").selectAll().where("id", "=", idp.id).executeTakeFirst();
501
- if (idpAlreadyExists) {
502
- throw new Error(`IDP ${idp.id} already exists`);
503
- } else {
504
- await trx.insertInto("idps").values(fromIdp(idp)).execute();
505
- }
506
- });
507
- }
508
- async removeIdp(idpId) {
509
- const networks = await this.listNetworks();
510
- if (networks.some((n) => n.identityProviderId === idpId)) {
511
- throw new Error(
512
- `Cannot delete IDP ${idpId} as it is in use by existing networks`
513
- );
514
- }
515
- await this.db.transaction().execute(async (trx) => {
516
- const idp = await trx.selectFrom("idps").selectAll().where("id", "=", idpId).executeTakeFirst();
517
- if (!idp) {
518
- throw new Error(`IDP ${idpId} does not exists`);
519
- }
520
- await trx.deleteFrom("idps").where("id", "=", idpId).execute();
521
- });
522
- }
523
- // Network methods
524
- async getNetwork(networkId) {
525
- this.assertConnected();
526
- const networks = await this.listNetworks();
527
- if (!networks) throw new Error("No networks available");
528
- const network = networks.find((n) => n.id === networkId);
529
- if (!network) throw new Error(`Network "${networkId}" not found`);
530
- return network;
531
- }
532
- async getCurrentNetwork() {
533
- const session = await this.getSession();
534
- if (!session) {
535
- throw new Error("No session found");
536
- }
537
- const networkId = session.network;
538
- if (!networkId) {
539
- throw new Error("No current network set in session");
540
- }
541
- const networks = await this.listNetworks();
542
- const network = networks.find((n) => n.id === networkId);
543
- if (!network) {
544
- throw new Error(`Network "${networkId}" not found`);
545
- }
546
- return network;
547
- }
548
- async listNetworks() {
549
- let query = this.db.selectFrom("networks").selectAll();
550
- if (this.authContext) {
551
- const userId = this.assertConnected();
552
- query = query.where(
553
- (eb) => eb.or([
554
- eb("userId", "is", null),
555
- // Global networks
556
- eb("userId", "=", userId)
557
- // User-specific networks
558
- ])
559
- );
560
- } else {
561
- query = query.where("userId", "is", null);
562
- }
563
- const networks = await query.execute();
564
- return networks.map((table) => toNetwork(table));
565
- }
566
- async updateNetwork(network) {
567
- this.assertConnected();
568
- await this.db.transaction().execute(async (trx) => {
569
- const networkEntry = fromNetwork(network, void 0);
570
- this.logger.info(networkEntry, "Updating network table");
571
- await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
572
- });
573
- }
574
- async addNetwork(network) {
575
- const userId = this.authContext?.userId;
576
- const idps = await this.listIdps();
577
- const networkIdp = idps.find(
578
- (idp) => idp.id === network.identityProviderId
579
- );
580
- if (!networkIdp) {
581
- throw new Error(
582
- `Identity provider "${network.identityProviderId}" not found`
583
- );
584
- }
585
- await this.db.transaction().execute(async (trx) => {
586
- const networkAlreadyExists = await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst();
587
- if (networkAlreadyExists) {
588
- throw new Error(`Network ${network.id} already exists`);
589
- } else {
590
- await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
591
- }
592
- });
593
- }
594
- async removeNetwork(networkId) {
595
- const userId = this.assertConnected();
596
- await this.db.transaction().execute(async (trx) => {
597
- const network = await trx.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
598
- if (!network) {
599
- throw new Error(`Network ${networkId} does not exists`);
600
- }
601
- if (network.userId !== userId) {
602
- throw new Error(
603
- `Network ${networkId} is not owned by user ${userId}`
604
- );
605
- }
606
- await trx.deleteFrom("networks").where("id", "=", networkId).execute();
607
- });
608
- }
609
- mergeTransactionStatusUpdate(existing, status, updates = {}) {
610
- const payload = updates.payload ?? existing.payload;
611
- const signedAt = updates.signedAt ?? existing.signedAt;
612
- const externalTxId = updates.externalTxId ?? existing.externalTxId;
613
- return {
614
- id: existing.id,
615
- commandId: existing.commandId,
616
- status,
617
- preparedTransaction: existing.preparedTransaction,
618
- preparedTransactionHash: existing.preparedTransactionHash,
619
- origin: existing.origin,
620
- ...payload !== void 0 && { payload },
621
- ...existing.createdAt !== void 0 && {
622
- createdAt: existing.createdAt
623
- },
624
- ...signedAt !== void 0 && { signedAt },
625
- ...externalTxId !== void 0 && { externalTxId }
626
- };
627
- }
628
- // Transaction methods
629
- async setTransaction(transaction) {
630
- const userId = this.assertConnected();
631
- const network = await this.getCurrentNetwork();
632
- await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
633
- }
634
- async setTransactionSigned(transactionId, signedAt, externalTxId) {
635
- await this.setTransactionStatus(transactionId, "signed", {
636
- signedAt,
637
- ...externalTxId !== void 0 && { externalTxId }
638
- });
639
- }
640
- async setTransactionStatus(transactionId, status, updates = {}) {
641
- const userId = this.assertConnected();
642
- const network = await this.getCurrentNetwork();
643
- const existing = await this.getTransaction(transactionId);
644
- if (!existing) {
645
- throw new Error(`Transaction not found with id: ${transactionId}`);
646
- }
647
- const updated = this.mergeTransactionStatusUpdate(
648
- existing,
649
- status,
650
- updates
651
- );
652
- await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where(
653
- (eb) => eb.and([
654
- eb("id", "=", transactionId),
655
- eb("userId", "=", userId),
656
- eb("networkId", "=", network.id)
657
- ])
658
- ).execute();
659
- }
660
- async getTransaction(transactionId) {
661
- const userId = this.assertConnected();
662
- const network = await this.getCurrentNetwork();
663
- const transaction = await this.db.selectFrom("transactions").selectAll().where(
664
- (eb) => eb.and([
665
- eb("id", "=", transactionId),
666
- eb("userId", "=", userId),
667
- eb("networkId", "=", network.id)
668
- ])
669
- ).executeTakeFirst();
670
- return transaction ? toTransaction(transaction) : void 0;
671
- }
672
- async getLatestTransactionByCommandId(commandId) {
673
- const userId = this.assertConnected();
674
- const network = await this.getCurrentNetwork();
675
- const transaction = await this.db.selectFrom("transactions").selectAll().where(
676
- (eb) => eb.and([
677
- eb("commandId", "=", commandId),
678
- eb("userId", "=", userId),
679
- eb("networkId", "=", network.id)
680
- ])
681
- ).orderBy("createdAt", "desc").orderBy("id", "desc").executeTakeFirst();
682
- return transaction ? toTransaction(transaction) : void 0;
683
- }
684
- async listTransactions() {
685
- const userId = this.assertConnected();
686
- const network = await this.getCurrentNetwork();
687
- const transactions = await this.db.selectFrom("transactions").selectAll().where(
688
- (eb) => eb.and([
689
- eb("userId", "=", userId),
690
- eb("networkId", "=", network.id)
691
- ])
692
- ).orderBy("createdAt", "desc").execute();
693
- return transactions.map((table) => toTransaction(table));
694
- }
695
- async removeTransaction(transactionId) {
696
- const userId = this.assertConnected();
697
- const network = await this.getCurrentNetwork();
698
- await this.db.deleteFrom("transactions").where(
699
- (eb) => eb.and([
700
- eb("id", "=", transactionId),
701
- eb("userId", "=", userId),
702
- eb("networkId", "=", network.id)
703
- ])
704
- ).execute();
705
- }
706
- mergeMessageRawStatusUpdate(existing, status, updates = {}) {
707
- const signedAt = updates.signedAt ?? existing.signedAt;
708
- const signature = updates.signature ?? existing.signature;
709
- return {
710
- ...existing,
711
- status,
712
- ...signedAt !== void 0 && { signedAt },
713
- ...signature !== void 0 && { signature }
714
- };
715
- }
716
- // Message signing request methods
717
- async setMessageRaw(message) {
718
- const userId = this.assertConnected();
719
- if (message.userId !== userId) {
720
- throw new Error(
721
- `MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`
722
- );
723
- }
724
- const network = await this.getCurrentNetwork();
725
- await this.db.insertInto("messagesRaw").values(fromMessageRaw(message, userId, network.id)).execute();
726
- }
727
- async setMessageRawStatus(messageId, status, updates = {}) {
728
- const userId = this.assertConnected();
729
- const network = await this.getCurrentNetwork();
730
- const existing = await this.getMessageRaw(messageId);
731
- if (!existing) {
732
- throw new Error(`MessageRaw not found with id: ${messageId}`);
733
- }
734
- const updated = this.mergeMessageRawStatusUpdate(
735
- existing,
736
- status,
737
- updates
738
- );
739
- await this.db.updateTable("messagesRaw").set(fromMessageRaw(updated, userId, network.id)).where(
740
- (eb) => eb.and([
741
- eb("id", "=", messageId),
742
- eb("userId", "=", userId),
743
- eb("networkId", "=", network.id)
744
- ])
745
- ).execute();
746
- }
747
- async getMessageRaw(messageId) {
748
- const userId = this.assertConnected();
749
- const network = await this.getCurrentNetwork();
750
- const message = await this.db.selectFrom("messagesRaw").selectAll().where(
751
- (eb) => eb.and([
752
- eb("id", "=", messageId),
753
- eb("userId", "=", userId),
754
- eb("networkId", "=", network.id)
755
- ])
756
- ).executeTakeFirst();
757
- return message ? toMessageRaw(message) : void 0;
758
- }
759
- async listMessageRaws() {
760
- const userId = this.assertConnected();
761
- const network = await this.getCurrentNetwork();
762
- const messages = await this.db.selectFrom("messagesRaw").selectAll().where(
763
- (eb) => eb.and([
764
- eb("userId", "=", userId),
765
- eb("networkId", "=", network.id)
766
- ])
767
- ).orderBy("createdAt", "desc").orderBy("id", "desc").execute();
768
- return messages.map((m) => toMessageRaw(m));
769
- }
770
- async removeMessageRaw(messageId) {
771
- const userId = this.assertConnected();
772
- const network = await this.getCurrentNetwork();
773
- await this.db.deleteFrom("messagesRaw").where(
774
- (eb) => eb.and([
775
- eb("id", "=", messageId),
776
- eb("userId", "=", userId),
777
- eb("networkId", "=", network.id)
778
- ])
779
- ).execute();
780
- }
781
- // API keys
782
- async addApiKey(apiKey) {
783
- const userId = this.assertConnected();
784
- if (apiKey.userId !== userId) {
785
- throw new Error(
786
- `ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`
787
- );
788
- }
789
- const network = await this.getCurrentNetwork();
790
- if (apiKey.networkId !== network.id) {
791
- throw new Error(
792
- `ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`
793
- );
794
- }
795
- await this.db.insertInto("apiKeys").values(toApiKey(apiKey)).execute();
796
- }
797
- async listApiKeys() {
798
- const query = this.db.selectFrom("apiKeys").selectAll().orderBy("createdAt", "desc");
799
- const userId = this.assertConnected();
800
- const network = await this.getCurrentNetwork();
801
- const apiKeys = await query.where(
802
- (eb) => eb.and([
803
- eb("userId", "=", userId),
804
- eb("networkId", "=", network.id)
805
- ])
806
- ).execute();
807
- return apiKeys.map(fromApiKey);
808
- }
809
- async getApiKey(digest) {
810
- const apiKey = await this.db.selectFrom("apiKeys").selectAll().where((eb) => eb("digest", "=", digest)).executeTakeFirst();
811
- return apiKey ? fromApiKey(apiKey) : void 0;
812
- }
813
- async removeApiKey(apiKeyId) {
814
- const userId = this.assertConnected();
815
- const network = await this.getCurrentNetwork();
816
- await this.db.deleteFrom("apiKeys").where(
817
- (eb) => eb.and([
818
- eb("id", "=", apiKeyId),
819
- eb("userId", "=", userId),
820
- eb("networkId", "=", network.id)
821
- ])
822
- ).execute();
823
- }
214
+ //#endregion
215
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
216
+ function _typeof(o) {
217
+ "@babel/helpers - typeof";
218
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
219
+ return typeof o;
220
+ } : function(o) {
221
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
222
+ }, _typeof(o);
223
+ }
224
+ //#endregion
225
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
226
+ function toPrimitive(t, r) {
227
+ if ("object" != _typeof(t) || !t) return t;
228
+ var e = t[Symbol.toPrimitive];
229
+ if (void 0 !== e) {
230
+ var i = e.call(t, r || "default");
231
+ if ("object" != _typeof(i)) return i;
232
+ throw new TypeError("@@toPrimitive must return a primitive value.");
233
+ }
234
+ return ("string" === r ? String : Number)(t);
235
+ }
236
+ //#endregion
237
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
238
+ function toPropertyKey(t) {
239
+ var i = toPrimitive(t, "string");
240
+ return "symbol" == _typeof(i) ? i : i + "";
241
+ }
242
+ //#endregion
243
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
244
+ function _defineProperty(e, r, t) {
245
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
246
+ value: t,
247
+ enumerable: !0,
248
+ configurable: !0,
249
+ writable: !0
250
+ }) : e[r] = t, e;
251
+ }
252
+ //#endregion
253
+ //#region src/store-sql.ts
254
+ var StoreSql = class StoreSql {
255
+ constructor(db, logger, authContext) {
256
+ this.db = db;
257
+ this.logger = logger;
258
+ _defineProperty(this, "authContext", void 0);
259
+ this.logger = logger.child({ component: "StoreSql" });
260
+ this.authContext = authContext;
261
+ }
262
+ withAuthContext(context) {
263
+ return new StoreSql(this.db, this.logger, context);
264
+ }
265
+ assertConnected() {
266
+ return assertConnected(this.authContext).userId;
267
+ }
268
+ async getAllWallets(filter = {}) {
269
+ const userId = this.assertConnected();
270
+ const { networkIds, signingProviderIds } = filter;
271
+ const networkIdSet = networkIds ? new Set(networkIds) : null;
272
+ const signingProviderIdSet = signingProviderIds ? new Set(signingProviderIds) : null;
273
+ const wallets = await this.db.selectFrom("wallets").selectAll().where("userId", "=", userId).execute();
274
+ const userPartyRights = await this.db.selectFrom("userPartyRights").selectAll().where("userId", "=", userId).execute();
275
+ const rightsByWallet = /* @__PURE__ */ new Map();
276
+ for (const row of userPartyRights) {
277
+ const right = fromPartyRight(row.right);
278
+ if (!right) continue;
279
+ const key = `${row.partyId}:${row.networkId}`;
280
+ const existing = rightsByWallet.get(key) ?? [];
281
+ rightsByWallet.set(key, [...existing, right]);
282
+ }
283
+ return wallets.filter((wallet) => {
284
+ const matchedNetworkIds = networkIdSet ? networkIdSet.has(wallet.networkId) : true;
285
+ const matchedSigningProviderIds = signingProviderIdSet ? signingProviderIdSet.has(wallet.signingProviderId) : true;
286
+ return matchedNetworkIds && matchedSigningProviderIds;
287
+ }).map((table) => {
288
+ const wallet = toWallet(table);
289
+ const rights = rightsByWallet.get(`${table.partyId}:${table.networkId}`);
290
+ return {
291
+ ...wallet,
292
+ rights: rights ?? []
293
+ };
294
+ });
295
+ }
296
+ async getWallets(filter = {}) {
297
+ const network = await this.getCurrentNetwork();
298
+ return this.getAllWallets({
299
+ ...filter,
300
+ networkIds: [network.id]
301
+ });
302
+ }
303
+ async getPrimaryWallet() {
304
+ return (await this.getWallets()).find((w) => w.primary === true);
305
+ }
306
+ async setPrimaryWallet(partyId) {
307
+ const network = await this.getCurrentNetwork();
308
+ const userId = this.assertConnected();
309
+ const wallets = await this.getWallets();
310
+ if (!wallets.some((w) => w.partyId === partyId)) throw new Error(`Wallet with partyId "${partyId}" not found in network "${network.id}"`);
311
+ const primary = wallets.find((w) => w.primary === true);
312
+ await this.db.transaction().execute(async (trx) => {
313
+ if (primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
314
+ eb("partyId", "=", primary.partyId),
315
+ eb("networkId", "=", network.id),
316
+ eb("userId", "=", userId)
317
+ ])).execute();
318
+ await trx.updateTable("wallets").set({ primary: 1 }).where((eb) => eb.and([
319
+ eb("partyId", "=", partyId),
320
+ eb("networkId", "=", network.id),
321
+ eb("userId", "=", userId)
322
+ ])).execute();
323
+ });
324
+ }
325
+ async addWallet(wallet) {
326
+ this.logger.info("Adding wallet");
327
+ const userId = this.assertConnected();
328
+ const wallets = await this.getWallets();
329
+ if (wallets.some((w) => w.partyId === wallet.partyId && w.networkId === wallet.networkId)) throw new Error(`Wallet with partyId "${wallet.partyId}" networkId "${wallet.networkId}" userId "${userId}" already exists`);
330
+ if (!wallet.disabled && wallet.status === "allocated" && !wallets.some((wallet) => wallet.primary)) wallet.primary = true;
331
+ await this.db.transaction().execute(async (trx) => {
332
+ if (wallet.primary) await trx.updateTable("wallets").set({ primary: 0 }).where((eb) => eb.and([
333
+ eb("primary", "=", 1),
334
+ eb("networkId", "=", wallet.networkId),
335
+ eb("userId", "=", userId)
336
+ ])).execute();
337
+ await trx.insertInto("wallets").values(fromWallet(wallet, userId)).execute();
338
+ if (wallet.rights && wallet.rights.length > 0) await trx.insertInto("userPartyRights").values(wallet.rights.map((right) => ({
339
+ userId,
340
+ networkId: wallet.networkId,
341
+ partyId: wallet.partyId,
342
+ right
343
+ }))).execute();
344
+ });
345
+ }
346
+ async updateWallet(params) {
347
+ const { partyId, networkId, rights } = params;
348
+ this.logger.info("Updating wallet");
349
+ const userId = this.assertConnected();
350
+ const updates = toWalletUpdateProperties(params);
351
+ const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
352
+ if (Object.keys(updates).length === 0 && rights === void 0) return;
353
+ await this.db.transaction().execute(async (trx) => {
354
+ if (Object.keys(updates).length > 0) await trx.updateTable("wallets").set(updates).where((eb) => eb.and([
355
+ eb("partyId", "=", partyId),
356
+ eb("networkId", "=", targetNetworkId),
357
+ eb("userId", "=", userId)
358
+ ])).execute();
359
+ if (rights !== void 0) {
360
+ await trx.deleteFrom("userPartyRights").where((eb) => eb.and([
361
+ eb("partyId", "=", partyId),
362
+ eb("networkId", "=", targetNetworkId),
363
+ eb("userId", "=", userId)
364
+ ])).execute();
365
+ if (rights.length > 0) await trx.insertInto("userPartyRights").values(rights.map((right) => ({
366
+ userId,
367
+ networkId: targetNetworkId,
368
+ partyId,
369
+ right
370
+ }))).execute();
371
+ }
372
+ });
373
+ }
374
+ async removeWallet(partyId) {
375
+ this.logger.info("Removing wallet");
376
+ const userId = this.assertConnected();
377
+ const network = await this.getCurrentNetwork();
378
+ await this.db.transaction().execute(async (trx) => {
379
+ await trx.deleteFrom("wallets").where((eb) => eb.and([
380
+ eb("partyId", "=", partyId),
381
+ eb("networkId", "=", network.id),
382
+ eb("userId", "=", userId)
383
+ ])).execute();
384
+ });
385
+ }
386
+ async getUserRights(networkId) {
387
+ const userId = this.assertConnected();
388
+ const targetNetworkId = networkId ?? (await this.getCurrentNetwork()).id;
389
+ return (await this.db.selectFrom("userRights").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", targetNetworkId)])).execute()).map((row) => fromUserRight(row.right)).filter((right) => right !== void 0);
390
+ }
391
+ async setUserRights(networkId, rights) {
392
+ const userId = this.assertConnected();
393
+ await this.db.transaction().execute(async (trx) => {
394
+ await trx.deleteFrom("userRights").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", networkId)])).execute();
395
+ if (rights.length > 0) await trx.insertInto("userRights").values(rights.map((right) => ({
396
+ userId,
397
+ networkId,
398
+ right
399
+ }))).execute();
400
+ });
401
+ }
402
+ async getSession(accessToken) {
403
+ const userId = this.assertConnected();
404
+ const row = await this.db.selectFrom("sessions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).executeTakeFirst();
405
+ return row ? toSession(row) : void 0;
406
+ }
407
+ async listSessions() {
408
+ const userId = this.assertConnected();
409
+ return (await this.db.selectFrom("sessions").selectAll().where("userId", "=", userId).execute()).map((row) => toSession(row));
410
+ }
411
+ async setSession(session) {
412
+ const userId = this.assertConnected();
413
+ if (!session.origin) throw new Error("Session origin is required");
414
+ await this.db.transaction().execute(async (trx) => {
415
+ const deleted = await trx.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("origin", "=", session.origin)])).execute();
416
+ this.logger.debug(deleted, "Deleted old session");
417
+ const inserted = await trx.insertInto("sessions").values({
418
+ ...session,
419
+ userId
420
+ }).execute();
421
+ this.logger.debug(inserted, "Inserted new session");
422
+ });
423
+ }
424
+ async removeSession(accessToken) {
425
+ const userId = this.assertConnected();
426
+ await this.db.deleteFrom("sessions").where((eb) => eb.and([eb("userId", "=", userId), eb("accessToken", "=", accessToken)])).execute();
427
+ }
428
+ /**
429
+ * Lists all pending transactions across all users.
430
+ */
431
+ async listAllPendingTransactions() {
432
+ return (await this.db.selectFrom("transactions").selectAll().where("status", "=", "pending").execute()).map((row) => toTransaction(row));
433
+ }
434
+ async getIdp(idpId) {
435
+ const idps = await this.listIdps();
436
+ if (!idps) throw new Error("No IDPs available");
437
+ const idp = idps.find((n) => n.id === idpId);
438
+ if (!idp) throw new Error(`IDP "${idpId}" not found`);
439
+ return idp;
440
+ }
441
+ async listIdps() {
442
+ return (await this.db.selectFrom("idps").selectAll().execute()).map((table) => toIdp(table));
443
+ }
444
+ async updateIdp(idp) {
445
+ await this.db.transaction().execute(async (trx) => {
446
+ const idpEntry = fromIdp(idp);
447
+ this.logger.info(idpEntry, "Updating idp table");
448
+ await trx.updateTable("idps").set(idpEntry).where("id", "=", idp.id).execute();
449
+ });
450
+ }
451
+ async addIdp(idp) {
452
+ await this.db.transaction().execute(async (trx) => {
453
+ if (await trx.selectFrom("idps").selectAll().where("id", "=", idp.id).executeTakeFirst()) throw new Error(`IDP ${idp.id} already exists`);
454
+ else await trx.insertInto("idps").values(fromIdp(idp)).execute();
455
+ });
456
+ }
457
+ async removeIdp(idpId) {
458
+ if ((await this.listNetworks()).some((n) => n.identityProviderId === idpId)) throw new Error(`Cannot delete IDP ${idpId} as it is in use by existing networks`);
459
+ await this.db.transaction().execute(async (trx) => {
460
+ if (!await trx.selectFrom("idps").selectAll().where("id", "=", idpId).executeTakeFirst()) throw new Error(`IDP ${idpId} does not exists`);
461
+ await trx.deleteFrom("idps").where("id", "=", idpId).execute();
462
+ });
463
+ }
464
+ async getNetwork(networkId) {
465
+ const networks = await this.listNetworks();
466
+ if (!networks) throw new Error("No networks available");
467
+ const network = networks.find((n) => n.id === networkId);
468
+ if (!network) throw new Error(`Network "${networkId}" not found`);
469
+ return network;
470
+ }
471
+ async getCurrentNetwork() {
472
+ const token = this.authContext?.accessToken;
473
+ if (!token) throw new Error("No access token found in auth context");
474
+ const session = await this.getSession(token);
475
+ if (!session) throw new Error("No session found");
476
+ const networkId = session.network;
477
+ if (!networkId) throw new Error("No current network set in session");
478
+ const network = (await this.listNetworks()).find((n) => n.id === networkId);
479
+ if (!network) throw new Error(`Network "${networkId}" not found`);
480
+ return network;
481
+ }
482
+ async listNetworks() {
483
+ let query = this.db.selectFrom("networks").selectAll();
484
+ if (this.authContext) {
485
+ const userId = this.assertConnected();
486
+ query = query.where((eb) => eb.or([eb("userId", "is", null), eb("userId", "=", userId)]));
487
+ } else query = query.where("userId", "is", null);
488
+ return (await query.execute()).map((table) => toNetwork(table));
489
+ }
490
+ async updateNetwork(network) {
491
+ this.assertConnected();
492
+ await this.db.transaction().execute(async (trx) => {
493
+ const networkEntry = fromNetwork(network, void 0);
494
+ this.logger.info(networkEntry, "Updating network table");
495
+ await trx.updateTable("networks").set(networkEntry).where("id", "=", network.id).execute();
496
+ });
497
+ }
498
+ async addNetwork(network) {
499
+ const userId = this.authContext?.userId;
500
+ if (!(await this.listIdps()).find((idp) => idp.id === network.identityProviderId)) throw new Error(`Identity provider "${network.identityProviderId}" not found`);
501
+ await this.db.transaction().execute(async (trx) => {
502
+ if (await trx.selectFrom("networks").selectAll().where("id", "=", network.id).executeTakeFirst()) throw new Error(`Network ${network.id} already exists`);
503
+ else await trx.insertInto("networks").values(fromNetwork(network, userId)).execute();
504
+ });
505
+ }
506
+ async removeNetwork(networkId) {
507
+ const userId = this.assertConnected();
508
+ await this.db.transaction().execute(async (trx) => {
509
+ const network = await trx.selectFrom("networks").selectAll().where("id", "=", networkId).executeTakeFirst();
510
+ if (!network) throw new Error(`Network ${networkId} does not exists`);
511
+ if (network.userId !== userId) throw new Error(`Network ${networkId} is not owned by user ${userId}`);
512
+ await trx.deleteFrom("networks").where("id", "=", networkId).execute();
513
+ });
514
+ }
515
+ mergeTransactionStatusUpdate(existing, status, updates = {}) {
516
+ const payload = updates.payload ?? existing.payload;
517
+ const signedAt = updates.signedAt ?? existing.signedAt;
518
+ const externalTxId = updates.externalTxId ?? existing.externalTxId;
519
+ return {
520
+ id: existing.id,
521
+ commandId: existing.commandId,
522
+ status,
523
+ preparedTransaction: existing.preparedTransaction,
524
+ preparedTransactionHash: existing.preparedTransactionHash,
525
+ origin: existing.origin,
526
+ ...payload !== void 0 && { payload },
527
+ ...existing.createdAt !== void 0 && { createdAt: existing.createdAt },
528
+ ...signedAt !== void 0 && { signedAt },
529
+ ...externalTxId !== void 0 && { externalTxId }
530
+ };
531
+ }
532
+ async setTransaction(transaction) {
533
+ const userId = this.assertConnected();
534
+ const network = await this.getCurrentNetwork();
535
+ await this.db.insertInto("transactions").values(fromTransaction(transaction, userId, network.id)).execute();
536
+ }
537
+ async setTransactionSigned(transactionId, signedAt, externalTxId) {
538
+ await this.setTransactionStatus(transactionId, "signed", {
539
+ signedAt,
540
+ ...externalTxId !== void 0 && { externalTxId }
541
+ });
542
+ }
543
+ async setTransactionStatus(transactionId, status, updates = {}) {
544
+ const userId = this.assertConnected();
545
+ const network = await this.getCurrentNetwork();
546
+ const existing = await this.getTransaction(transactionId);
547
+ if (!existing) throw new Error(`Transaction not found with id: ${transactionId}`);
548
+ const updated = this.mergeTransactionStatusUpdate(existing, status, updates);
549
+ await this.db.updateTable("transactions").set(fromTransaction(updated, userId, network.id)).where((eb) => eb.and([
550
+ eb("id", "=", transactionId),
551
+ eb("userId", "=", userId),
552
+ eb("networkId", "=", network.id)
553
+ ])).execute();
554
+ }
555
+ async getTransaction(transactionId) {
556
+ const userId = this.assertConnected();
557
+ const network = await this.getCurrentNetwork();
558
+ const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
559
+ eb("id", "=", transactionId),
560
+ eb("userId", "=", userId),
561
+ eb("networkId", "=", network.id)
562
+ ])).executeTakeFirst();
563
+ return transaction ? toTransaction(transaction) : void 0;
564
+ }
565
+ async getLatestTransactionByCommandId(commandId) {
566
+ const userId = this.assertConnected();
567
+ const network = await this.getCurrentNetwork();
568
+ const transaction = await this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([
569
+ eb("commandId", "=", commandId),
570
+ eb("userId", "=", userId),
571
+ eb("networkId", "=", network.id)
572
+ ])).orderBy(sql`${sql.ref("createdAt")} desc nulls last`).executeTakeFirst();
573
+ return transaction ? toTransaction(transaction) : void 0;
574
+ }
575
+ async transactionsCount() {
576
+ const userId = this.assertConnected();
577
+ const network = await this.getCurrentNetwork();
578
+ const result = await this.db.selectFrom("transactions").where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).select((eb) => eb.fn.count("id").as("count")).executeTakeFirstOrThrow();
579
+ return Number(result.count);
580
+ }
581
+ async listTransactions(options) {
582
+ const userId = this.assertConnected();
583
+ const network = await this.getCurrentNetwork();
584
+ const { cursor, limit } = options ?? {};
585
+ const lim = limit ? Math.min(limit, 100) : 100;
586
+ let query = this.db.selectFrom("transactions").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy(sql`${sql.ref("createdAt")} desc nulls last`).orderBy("id", "desc").limit(lim + 1);
587
+ if (cursor) {
588
+ const split = cursor.split("::");
589
+ const dateString = split[0] === "null" ? null : split[0];
590
+ const cursorId = split[1];
591
+ query = query.where((eb) => {
592
+ if (dateString === null) return eb.and([eb("createdAt", "is", null), eb("id", "<", cursorId)]);
593
+ return eb.or([
594
+ eb("createdAt", "<", dateString),
595
+ eb.and([eb("createdAt", "=", dateString), eb("id", "<", split[1])]),
596
+ eb("createdAt", "is", null)
597
+ ]);
598
+ });
599
+ }
600
+ const txs = (await query.execute()).map((r) => toTransaction(r));
601
+ const hasNextPage = txs.length > lim;
602
+ if (hasNextPage) txs.pop();
603
+ if (txs.length === 0) return {
604
+ transactions: [],
605
+ nextCursor: null
606
+ };
607
+ const lastTx = txs[txs.length - 1];
608
+ if (lastTx === void 0) return {
609
+ transactions: txs,
610
+ nextCursor: null
611
+ };
612
+ if (lastTx.createdAt) {
613
+ const d = new Date(lastTx.createdAt).toISOString();
614
+ return {
615
+ transactions: txs,
616
+ nextCursor: hasNextPage ? `${d}::${lastTx.id}` : null
617
+ };
618
+ } else return {
619
+ transactions: txs,
620
+ nextCursor: hasNextPage ? `null::${lastTx.id}` : null
621
+ };
622
+ }
623
+ async removeTransaction(transactionId) {
624
+ const userId = this.assertConnected();
625
+ const network = await this.getCurrentNetwork();
626
+ await this.db.deleteFrom("transactions").where((eb) => eb.and([
627
+ eb("id", "=", transactionId),
628
+ eb("userId", "=", userId),
629
+ eb("networkId", "=", network.id)
630
+ ])).execute();
631
+ }
632
+ mergeMessageRawStatusUpdate(existing, status, updates = {}) {
633
+ const signedAt = updates.signedAt ?? existing.signedAt;
634
+ const signature = updates.signature ?? existing.signature;
635
+ return {
636
+ ...existing,
637
+ status,
638
+ ...signedAt !== void 0 && { signedAt },
639
+ ...signature !== void 0 && { signature }
640
+ };
641
+ }
642
+ async setMessageRaw(message) {
643
+ const userId = this.assertConnected();
644
+ if (message.userId !== userId) throw new Error(`MessageRaw userId mismatch: expected ${userId}, got ${message.userId}`);
645
+ const network = await this.getCurrentNetwork();
646
+ await this.db.insertInto("messagesRaw").values(fromMessageRaw(message, userId, network.id)).execute();
647
+ }
648
+ async setMessageRawStatus(messageId, status, updates = {}) {
649
+ const userId = this.assertConnected();
650
+ const network = await this.getCurrentNetwork();
651
+ const existing = await this.getMessageRaw(messageId);
652
+ if (!existing) throw new Error(`MessageRaw not found with id: ${messageId}`);
653
+ const updated = this.mergeMessageRawStatusUpdate(existing, status, updates);
654
+ await this.db.updateTable("messagesRaw").set(fromMessageRaw(updated, userId, network.id)).where((eb) => eb.and([
655
+ eb("id", "=", messageId),
656
+ eb("userId", "=", userId),
657
+ eb("networkId", "=", network.id)
658
+ ])).execute();
659
+ }
660
+ async getMessageRaw(messageId) {
661
+ const userId = this.assertConnected();
662
+ const network = await this.getCurrentNetwork();
663
+ const message = await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([
664
+ eb("id", "=", messageId),
665
+ eb("userId", "=", userId),
666
+ eb("networkId", "=", network.id)
667
+ ])).executeTakeFirst();
668
+ return message ? toMessageRaw(message) : void 0;
669
+ }
670
+ async listMessageRaws() {
671
+ const userId = this.assertConnected();
672
+ const network = await this.getCurrentNetwork();
673
+ return (await this.db.selectFrom("messagesRaw").selectAll().where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).orderBy("createdAt", "desc").orderBy("id", "desc").execute()).map((m) => toMessageRaw(m));
674
+ }
675
+ async removeMessageRaw(messageId) {
676
+ const userId = this.assertConnected();
677
+ const network = await this.getCurrentNetwork();
678
+ await this.db.deleteFrom("messagesRaw").where((eb) => eb.and([
679
+ eb("id", "=", messageId),
680
+ eb("userId", "=", userId),
681
+ eb("networkId", "=", network.id)
682
+ ])).execute();
683
+ }
684
+ async addApiKey(apiKey) {
685
+ const userId = this.assertConnected();
686
+ if (apiKey.userId !== userId) throw new Error(`ApiKey userId mismatch: expected ${userId}, got ${apiKey.userId}`);
687
+ const network = await this.getCurrentNetwork();
688
+ if (apiKey.networkId !== network.id) throw new Error(`ApiKey networkId mismatch: expected ${network.id}, got ${apiKey.networkId}`);
689
+ await this.db.insertInto("apiKeys").values(toApiKey(apiKey)).execute();
690
+ }
691
+ async listApiKeys() {
692
+ const query = this.db.selectFrom("apiKeys").selectAll().orderBy("createdAt", "desc");
693
+ const userId = this.assertConnected();
694
+ const network = await this.getCurrentNetwork();
695
+ return (await query.where((eb) => eb.and([eb("userId", "=", userId), eb("networkId", "=", network.id)])).execute()).map(fromApiKey);
696
+ }
697
+ async getApiKey(digest) {
698
+ const apiKey = await this.db.selectFrom("apiKeys").selectAll().where((eb) => eb("digest", "=", digest)).executeTakeFirst();
699
+ return apiKey ? fromApiKey(apiKey) : void 0;
700
+ }
701
+ async removeApiKey(apiKeyId) {
702
+ const userId = this.assertConnected();
703
+ const network = await this.getCurrentNetwork();
704
+ await this.db.deleteFrom("apiKeys").where((eb) => eb.and([
705
+ eb("id", "=", apiKeyId),
706
+ eb("userId", "=", userId),
707
+ eb("networkId", "=", network.id)
708
+ ])).execute();
709
+ }
824
710
  };
825
- var connection = (config) => {
826
- let database;
827
- switch (config.connection.type) {
828
- case "sqlite":
829
- database = new Database(config.connection.database);
830
- database.pragma("foreign_keys = ON");
831
- return new Kysely({
832
- dialect: new SqliteDialect({
833
- database
834
- }),
835
- plugins: [new CamelCasePlugin()]
836
- });
837
- case "postgres":
838
- return new Kysely({
839
- dialect: new PostgresDialect({
840
- pool: new pg.Pool(config.connection)
841
- }),
842
- plugins: [new CamelCasePlugin()]
843
- });
844
- case "memory":
845
- database = new Database(":memory:");
846
- database.pragma("foreign_keys = ON");
847
- return new Kysely({
848
- dialect: new SqliteDialect({
849
- database
850
- }),
851
- plugins: [new CamelCasePlugin()]
852
- });
853
- }
711
+ const connection = (config) => {
712
+ let database;
713
+ switch (config.connection.type) {
714
+ case "sqlite":
715
+ database = new Database(config.connection.database);
716
+ database.pragma("foreign_keys = ON");
717
+ return new Kysely({
718
+ dialect: new SqliteDialect({ database }),
719
+ plugins: [new CamelCasePlugin()]
720
+ });
721
+ case "postgres": return new Kysely({
722
+ dialect: new PostgresDialect({ pool: new pg.Pool(config.connection) }),
723
+ plugins: [new CamelCasePlugin()]
724
+ });
725
+ case "memory":
726
+ database = new Database(":memory:");
727
+ database.pragma("foreign_keys = ON");
728
+ return new Kysely({
729
+ dialect: new SqliteDialect({ database }),
730
+ plugins: [new CamelCasePlugin()]
731
+ });
732
+ }
854
733
  };
734
+ //#endregion
735
+ //#region src/migrator.ts
855
736
  var KyselyStorage = class {
856
- constructor(db) {
857
- this.db = db;
858
- }
859
- async ensureTable() {
860
- await this.db.schema.createTable("migrations").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("executedAt", "text", (col) => col.notNull()).execute();
861
- }
862
- async executed() {
863
- await this.ensureTable();
864
- const rows = await this.db.selectFrom("migrations").select("name").execute();
865
- return rows.map((r) => r.name);
866
- }
867
- async logMigration({ name }) {
868
- await this.ensureTable();
869
- await this.db.insertInto("migrations").values({ name, executedAt: (/* @__PURE__ */ new Date()).toISOString() }).execute();
870
- }
871
- async unlogMigration({ name }) {
872
- await this.ensureTable();
873
- await this.db.deleteFrom("migrations").where("name", "=", name).execute();
874
- }
737
+ constructor(db) {
738
+ this.db = db;
739
+ }
740
+ async ensureTable() {
741
+ await this.db.schema.createTable("migrations").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("executedAt", "text", (col) => col.notNull()).execute();
742
+ }
743
+ async executed() {
744
+ await this.ensureTable();
745
+ return (await this.db.selectFrom("migrations").select("name").execute()).map((r) => r.name);
746
+ }
747
+ async logMigration({ name }) {
748
+ await this.ensureTable();
749
+ await this.db.insertInto("migrations").values({
750
+ name,
751
+ executedAt: (/* @__PURE__ */ new Date()).toISOString()
752
+ }).execute();
753
+ }
754
+ async unlogMigration({ name }) {
755
+ await this.ensureTable();
756
+ await this.db.deleteFrom("migrations").where("name", "=", name).execute();
757
+ }
875
758
  };
876
- var migrator = (db) => {
877
- const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
878
- const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname;
879
- return new Umzug({
880
- migrations: {
881
- glob,
882
- resolve: ({ name, path, context }) => {
883
- return {
884
- name,
885
- up: async () => {
886
- console.log(path);
887
- const { up } = await import(path);
888
- return up(context);
889
- },
890
- down: async () => {
891
- const { down } = await import(path);
892
- return down(context);
893
- }
894
- };
895
- }
896
- },
897
- context: db,
898
- storage: new KyselyStorage(db),
899
- logger: console
900
- });
759
+ const migrator = (db) => {
760
+ const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
761
+ const glob = new URL(`./migrations/*.${ext}`, import.meta.url).pathname;
762
+ return new Umzug({
763
+ migrations: {
764
+ glob,
765
+ resolve: ({ name, path, context }) => {
766
+ return {
767
+ name,
768
+ up: async () => {
769
+ console.log(path);
770
+ const { up } = await import(path);
771
+ return up(context);
772
+ },
773
+ down: async () => {
774
+ const { down } = await import(path);
775
+ return down(context);
776
+ }
777
+ };
778
+ }
779
+ },
780
+ context: db,
781
+ storage: new KyselyStorage(db),
782
+ logger: console
783
+ });
901
784
  };
902
-
903
- // src/bootstrap.ts
904
- async function bootstrap(db, config, logger2) {
905
- const store = new StoreSql(db, logger2);
906
- await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
907
- await Promise.all(
908
- config.networks.map((network) => store.addNetwork(network))
909
- );
785
+ //#endregion
786
+ //#region src/bootstrap.ts
787
+ async function bootstrap(db, config, logger) {
788
+ const store = new StoreSql(db, logger);
789
+ await Promise.all(config.idps.map((idp) => store.addIdp(idp)));
790
+ await Promise.all(config.networks.map((network) => store.addNetwork(network)));
910
791
  }
911
-
912
- // src/cli.ts
913
- var logger = pino({ name: "main", level: "debug" });
792
+ //#endregion
793
+ //#region src/cli.ts
794
+ const logger = pino({
795
+ name: "main",
796
+ level: "debug"
797
+ });
914
798
  function createCLI(config, bootstrapConfig) {
915
- const program = new Command();
916
- program.command("up").description("Run all pending migrations").action(async () => {
917
- const db = connection(config);
918
- const umzug = migrator(db);
919
- await umzug.up();
920
- await db.destroy();
921
- });
922
- program.command("down").description("Rollback last migration").action(async () => {
923
- const db = connection(config);
924
- const umzug = migrator(db);
925
- await umzug.down();
926
- await db.destroy();
927
- });
928
- program.command("status").description("Show executed and pending migrations").action(async () => {
929
- const db = connection(config);
930
- const umzug = migrator(db);
931
- const executed = await umzug.executed();
932
- const pending = await umzug.pending();
933
- console.log("Executed migrations:", executed);
934
- console.log("Pending migrations:", pending);
935
- await db.destroy();
936
- });
937
- program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
938
- const db = connection(config);
939
- const umzug = migrator(db);
940
- const executed = await umzug.executed();
941
- for (const migration of executed.reverse()) {
942
- await umzug.down({ to: migration.name });
943
- }
944
- await umzug.up();
945
- await db.destroy();
946
- });
947
- program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
948
- if (!bootstrapConfig) {
949
- throw new Error(
950
- "Bootstrap config (idps/networks) is required for the bootstrap command"
951
- );
952
- }
953
- const db = connection(config);
954
- await bootstrap(db, bootstrapConfig, logger);
955
- await db.destroy();
956
- });
957
- return program;
799
+ const program = new Command();
800
+ program.command("up").description("Run all pending migrations").action(async () => {
801
+ const db = connection(config);
802
+ await migrator(db).up();
803
+ await db.destroy();
804
+ });
805
+ program.command("down").description("Rollback last migration").action(async () => {
806
+ const db = connection(config);
807
+ await migrator(db).down();
808
+ await db.destroy();
809
+ });
810
+ program.command("status").description("Show executed and pending migrations").action(async () => {
811
+ const db = connection(config);
812
+ const umzug = migrator(db);
813
+ const executed = await umzug.executed();
814
+ const pending = await umzug.pending();
815
+ console.log("Executed migrations:", executed);
816
+ console.log("Pending migrations:", pending);
817
+ await db.destroy();
818
+ });
819
+ program.command("reset").description("Rollback all migrations and reapply them").action(async () => {
820
+ const db = connection(config);
821
+ const umzug = migrator(db);
822
+ const executed = await umzug.executed();
823
+ for (const migration of executed.reverse()) await umzug.down({ to: migration.name });
824
+ await umzug.up();
825
+ await db.destroy();
826
+ });
827
+ program.command("bootstrap").description("Bootstrap DB from config").action(async () => {
828
+ if (!bootstrapConfig) throw new Error("Bootstrap config (idps/networks) is required for the bootstrap command");
829
+ const db = connection(config);
830
+ await bootstrap(db, bootstrapConfig, logger);
831
+ await db.destroy();
832
+ });
833
+ return program;
958
834
  }
959
-
835
+ //#endregion
960
836
  export { StoreSql, bootstrap, connection, createCLI, migrator };
961
- //# sourceMappingURL=index.js.map
837
+
962
838
  //# sourceMappingURL=index.js.map