@agentbadge/database 0.6.5 → 0.6.6

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.
@@ -0,0 +1,246 @@
1
+ import { isUniqueViolation } from "./commerce-repository.js";
2
+ const catchUnique = async (p) => {
3
+ try {
4
+ return await p;
5
+ }
6
+ catch (err) {
7
+ if (isUniqueViolation(err))
8
+ return null;
9
+ throw err;
10
+ }
11
+ };
12
+ const numOrNull = (v) => v == null ? null : Number(v);
13
+ const bigOrNull = (n) => n == null ? null : BigInt(n);
14
+ const toActorRow = (r) => ({
15
+ wallet: r.wallet,
16
+ type: r.type,
17
+ agentId: r.agentId,
18
+ passportTokenId: r.passportTokenId,
19
+ did: r.did,
20
+ orgId: r.orgId,
21
+ tier: r.tier,
22
+ payload: r.payload,
23
+ createdAt: r.createdAt,
24
+ updatedAt: r.updatedAt,
25
+ });
26
+ const entActiveSlot = (e) => e.status === "ACTIVE" ? `${e.ownerId}|${e.productCode}` : null;
27
+ const toEntitlementRow = (r) => ({
28
+ id: r.id,
29
+ ownerId: r.ownerId,
30
+ productCode: r.productCode,
31
+ sourcePaymentId: r.sourcePaymentId,
32
+ status: r.status,
33
+ validFromMs: Number(r.validFromMs),
34
+ validUntilMs: numOrNull(r.validUntilMs),
35
+ idempotencyKey: r.idempotencyKey,
36
+ activeSlot: r.activeSlot,
37
+ payload: r.payload,
38
+ createdAt: r.createdAt,
39
+ updatedAt: r.updatedAt,
40
+ });
41
+ const toFactRow = (r) => ({
42
+ id: r.id,
43
+ actorWallet: r.actorWallet,
44
+ factType: r.factType,
45
+ subjectId: r.subjectId,
46
+ sourceRef: r.sourceRef,
47
+ dedupeKey: r.dedupeKey,
48
+ atMs: Number(r.atMs),
49
+ payload: r.payload,
50
+ createdAt: r.createdAt,
51
+ });
52
+ export class ActorRepository {
53
+ db;
54
+ constructor(db) {
55
+ this.db = db;
56
+ }
57
+ get orm() {
58
+ return this.db.orm.public.Actor;
59
+ }
60
+ async upsert(a) {
61
+ const update = {
62
+ type: a.type,
63
+ payload: a.payload,
64
+ };
65
+ for (const key of [
66
+ "agentId",
67
+ "passportTokenId",
68
+ "did",
69
+ "orgId",
70
+ "tier",
71
+ ]) {
72
+ if (a[key] !== undefined)
73
+ update[key] = a[key];
74
+ }
75
+ const row = await this.orm.upsert({
76
+ create: {
77
+ wallet: a.wallet,
78
+ type: a.type,
79
+ agentId: a.agentId ?? null,
80
+ passportTokenId: a.passportTokenId ?? null,
81
+ did: a.did ?? null,
82
+ orgId: a.orgId ?? null,
83
+ tier: a.tier ?? null,
84
+ payload: a.payload,
85
+ },
86
+ update: update,
87
+ conflictOn: { wallet: a.wallet },
88
+ });
89
+ return toActorRow(row);
90
+ }
91
+ async getById(wallet) {
92
+ const r = await this.orm.where({ wallet }).first();
93
+ return r ? toActorRow(r) : null;
94
+ }
95
+ async list(opts) {
96
+ let q = this.orm.orderBy((t) => t.createdAt.desc());
97
+ if (opts?.type !== undefined)
98
+ q = q.where({ type: opts.type });
99
+ if (opts?.limit !== undefined)
100
+ q = q.limit(opts.limit);
101
+ return (await q.all()).map(toActorRow);
102
+ }
103
+ }
104
+ export class EntitlementRepository {
105
+ db;
106
+ constructor(db) {
107
+ this.db = db;
108
+ }
109
+ get orm() {
110
+ return this.db.orm.public.Entitlement;
111
+ }
112
+ async grant(e) {
113
+ if (await this.getById(e.id))
114
+ return null;
115
+ if (await this.getByIdempotencyKey(e.idempotencyKey))
116
+ return null;
117
+ const row = await catchUnique(this.orm.create({
118
+ id: e.id,
119
+ ownerId: e.ownerId,
120
+ productCode: e.productCode,
121
+ sourcePaymentId: e.sourcePaymentId ?? null,
122
+ status: e.status,
123
+ validFromMs: BigInt(e.validFromMs),
124
+ validUntilMs: bigOrNull(e.validUntilMs),
125
+ idempotencyKey: e.idempotencyKey,
126
+ activeSlot: entActiveSlot(e),
127
+ payload: e.payload,
128
+ }));
129
+ return row ? toEntitlementRow(row) : null;
130
+ }
131
+ async getById(id) {
132
+ const r = await this.orm.where({ id }).first();
133
+ return r ? toEntitlementRow(r) : null;
134
+ }
135
+ async getByIdempotencyKey(key) {
136
+ const r = await this.orm.where({ idempotencyKey: key }).first();
137
+ return r ? toEntitlementRow(r) : null;
138
+ }
139
+ async getActive(ownerId, productCode) {
140
+ const r = await this.orm
141
+ .where({ ownerId, productCode, status: "ACTIVE" })
142
+ .first();
143
+ return r ? toEntitlementRow(r) : null;
144
+ }
145
+ async listByOwner(ownerId, opts) {
146
+ let q = this.orm.where({ ownerId }).orderBy((t) => t.createdAt.desc());
147
+ if (opts?.status !== undefined)
148
+ q = q.where({ status: opts.status });
149
+ if (opts?.productCode !== undefined)
150
+ q = q.where({ productCode: opts.productCode });
151
+ if (opts?.limit !== undefined)
152
+ q = q.limit(opts.limit);
153
+ return (await q.all()).map(toEntitlementRow);
154
+ }
155
+ async listExpiring(nowMs, limit) {
156
+ const need = limit ?? 50;
157
+ const rows = (await this.orm
158
+ .where({ status: "ACTIVE" })
159
+ .orderBy((t) => t.validUntilMs.asc())
160
+ .limit(need * 4)
161
+ .all())
162
+ .map(toEntitlementRow)
163
+ .filter((r) => r.validUntilMs != null && r.validUntilMs <= nowMs);
164
+ return rows.slice(0, need);
165
+ }
166
+ async applyStatus(id, expectedFrom, to) {
167
+ const existing = await this.getById(id);
168
+ if (!existing || existing.status !== expectedFrom)
169
+ return null;
170
+ const slot = entActiveSlot({ ...existing, status: to });
171
+ const row = await catchUnique(this.orm.where({ id, status: expectedFrom }).update({
172
+ status: to,
173
+ activeSlot: slot,
174
+ }));
175
+ return row ? toEntitlementRow(row) : null;
176
+ }
177
+ }
178
+ export class ReputationFactRepository {
179
+ db;
180
+ constructor(db) {
181
+ this.db = db;
182
+ }
183
+ get orm() {
184
+ return this.db.orm.public.ReputationFact;
185
+ }
186
+ async append(f) {
187
+ if (await this.getById(f.id))
188
+ return null;
189
+ const dup = await this.orm.where({ dedupeKey: f.dedupeKey }).first();
190
+ if (dup)
191
+ return null;
192
+ const row = await catchUnique(this.orm.create({
193
+ id: f.id,
194
+ actorWallet: f.actorWallet,
195
+ factType: f.factType,
196
+ subjectId: f.subjectId ?? null,
197
+ sourceRef: f.sourceRef,
198
+ dedupeKey: f.dedupeKey,
199
+ atMs: BigInt(f.atMs),
200
+ payload: f.payload,
201
+ }));
202
+ return row ? toFactRow(row) : null;
203
+ }
204
+ async getById(id) {
205
+ const r = await this.orm.where({ id }).first();
206
+ return r ? toFactRow(r) : null;
207
+ }
208
+ async listByActor(actorWallet, opts) {
209
+ let q = this.orm
210
+ .where({ actorWallet })
211
+ .orderBy((t) => t.createdAt.desc());
212
+ if (opts?.factType !== undefined)
213
+ q = q.where({ factType: opts.factType });
214
+ if (opts?.limit !== undefined)
215
+ q = q.limit(opts.limit);
216
+ return (await q.all()).map(toFactRow);
217
+ }
218
+ async countsByActor(actorWallet) {
219
+ const rows = await this.orm.where({ actorWallet }).all();
220
+ const out = {};
221
+ for (const r of rows)
222
+ out[r.factType] = (out[r.factType] ?? 0) + 1;
223
+ return out;
224
+ }
225
+ }
226
+ export function createPrismaIdentityStores(db) {
227
+ const bundle = (client) => ({
228
+ actors: new ActorRepository(client),
229
+ entitlements: new EntitlementRepository(client),
230
+ facts: new ReputationFactRepository(client),
231
+ atomic: outerAtomic,
232
+ });
233
+ async function outerAtomic(fn) {
234
+ for (let attempt = 0;; attempt++) {
235
+ try {
236
+ return await db.transaction((tx) => fn(bundle(tx)));
237
+ }
238
+ catch (err) {
239
+ if (attempt === 0 && isUniqueViolation(err))
240
+ continue;
241
+ throw err;
242
+ }
243
+ }
244
+ }
245
+ return bundle(db);
246
+ }
@@ -0,0 +1,114 @@
1
+ import type { JsonValue } from "@prisma/orm-postgres/target/codec-types";
2
+ export interface ActorUpsert {
3
+ wallet: string;
4
+ type: string;
5
+ agentId?: string | null;
6
+ passportTokenId?: string | null;
7
+ did?: string | null;
8
+ orgId?: string | null;
9
+ tier?: string | null;
10
+ payload: JsonValue;
11
+ }
12
+ export interface ActorRow extends ActorUpsert {
13
+ createdAt: string;
14
+ updatedAt: string;
15
+ }
16
+ export interface ActorStore {
17
+ upsert(a: ActorUpsert): Promise<ActorRow>;
18
+ getById(wallet: string): Promise<ActorRow | null>;
19
+ list(opts?: {
20
+ type?: string;
21
+ limit?: number;
22
+ }): Promise<ActorRow[]>;
23
+ }
24
+ export interface EntitlementInsert {
25
+ id: string;
26
+ ownerId: string;
27
+ productCode: string;
28
+ sourcePaymentId?: string | null;
29
+ status: string;
30
+ validFromMs: number;
31
+ validUntilMs?: number | null;
32
+ idempotencyKey: string;
33
+ payload: JsonValue;
34
+ }
35
+ export interface EntitlementRow extends EntitlementInsert {
36
+ activeSlot: string | null;
37
+ createdAt: string;
38
+ updatedAt: string;
39
+ }
40
+ export interface EntitlementStore {
41
+ grant(e: EntitlementInsert): Promise<EntitlementRow | null>;
42
+ getById(id: string): Promise<EntitlementRow | null>;
43
+ getByIdempotencyKey(key: string): Promise<EntitlementRow | null>;
44
+ getActive(ownerId: string, productCode: string): Promise<EntitlementRow | null>;
45
+ listByOwner(ownerId: string, opts?: {
46
+ status?: string;
47
+ productCode?: string;
48
+ limit?: number;
49
+ }): Promise<EntitlementRow[]>;
50
+ listExpiring(nowMs: number, limit?: number): Promise<EntitlementRow[]>;
51
+ applyStatus(id: string, expectedFrom: string, to: string): Promise<EntitlementRow | null>;
52
+ }
53
+ export interface ReputationFactInsert {
54
+ id: string;
55
+ actorWallet: string;
56
+ factType: string;
57
+ subjectId?: string | null;
58
+ sourceRef: string;
59
+ dedupeKey: string;
60
+ atMs: number;
61
+ payload: JsonValue;
62
+ }
63
+ export interface ReputationFactRow extends ReputationFactInsert {
64
+ createdAt: string;
65
+ }
66
+ export interface ReputationFactStore {
67
+ append(f: ReputationFactInsert): Promise<ReputationFactRow | null>;
68
+ getById(id: string): Promise<ReputationFactRow | null>;
69
+ listByActor(actorWallet: string, opts?: {
70
+ factType?: string;
71
+ limit?: number;
72
+ }): Promise<ReputationFactRow[]>;
73
+ countsByActor(actorWallet: string): Promise<Record<string, number>>;
74
+ }
75
+ export interface IdentityStores {
76
+ actors: ActorStore;
77
+ entitlements: EntitlementStore;
78
+ facts: ReputationFactStore;
79
+ atomic<R>(fn: (stores: IdentityStores) => Promise<R>): Promise<R>;
80
+ }
81
+ export declare class InMemoryActorStore implements ActorStore {
82
+ private readonly rows;
83
+ upsert(a: ActorUpsert): Promise<ActorRow>;
84
+ getById(wallet: string): Promise<ActorRow | null>;
85
+ list(opts?: {
86
+ type?: string;
87
+ limit?: number;
88
+ }): Promise<ActorRow[]>;
89
+ }
90
+ export declare class InMemoryEntitlementStore implements EntitlementStore {
91
+ private readonly rows;
92
+ grant(e: EntitlementInsert): Promise<EntitlementRow | null>;
93
+ getById(id: string): Promise<EntitlementRow | null>;
94
+ getByIdempotencyKey(key: string): Promise<EntitlementRow | null>;
95
+ getActive(ownerId: string, productCode: string): Promise<EntitlementRow | null>;
96
+ listByOwner(ownerId: string, opts?: {
97
+ status?: string;
98
+ productCode?: string;
99
+ limit?: number;
100
+ }): Promise<EntitlementRow[]>;
101
+ listExpiring(nowMs: number, limit?: number): Promise<EntitlementRow[]>;
102
+ applyStatus(id: string, expectedFrom: string, to: string): Promise<EntitlementRow | null>;
103
+ }
104
+ export declare class InMemoryReputationFactStore implements ReputationFactStore {
105
+ private readonly rows;
106
+ append(f: ReputationFactInsert): Promise<ReputationFactRow | null>;
107
+ getById(id: string): Promise<ReputationFactRow | null>;
108
+ listByActor(actorWallet: string, opts?: {
109
+ factType?: string;
110
+ limit?: number;
111
+ }): Promise<ReputationFactRow[]>;
112
+ countsByActor(actorWallet: string): Promise<Record<string, number>>;
113
+ }
114
+ export declare function createInMemoryIdentityStores(): IdentityStores;
@@ -0,0 +1,170 @@
1
+ const nowIso = () => new Date().toISOString();
2
+ const entActiveSlot = (e) => e.status === "ACTIVE" ? `${e.ownerId}|${e.productCode}` : null;
3
+ export class InMemoryActorStore {
4
+ rows = new Map();
5
+ async upsert(a) {
6
+ const ts = nowIso();
7
+ const existing = this.rows.get(a.wallet);
8
+ const merge = (key) => (a[key] === undefined ? existing?.[key] : a[key]) ?? null;
9
+ const row = {
10
+ wallet: a.wallet,
11
+ type: a.type,
12
+ agentId: merge("agentId"),
13
+ passportTokenId: merge("passportTokenId"),
14
+ did: merge("did"),
15
+ orgId: merge("orgId"),
16
+ tier: merge("tier"),
17
+ payload: a.payload,
18
+ createdAt: existing?.createdAt ?? ts,
19
+ updatedAt: ts,
20
+ };
21
+ this.rows.set(row.wallet, row);
22
+ return row;
23
+ }
24
+ async getById(wallet) {
25
+ return this.rows.get(wallet) ?? null;
26
+ }
27
+ async list(opts) {
28
+ let out = [...this.rows.values()].filter((r) => opts?.type === undefined || r.type === opts.type);
29
+ out = out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
30
+ if (opts?.limit !== undefined)
31
+ out = out.slice(0, opts.limit);
32
+ return out;
33
+ }
34
+ }
35
+ export class InMemoryEntitlementStore {
36
+ rows = new Map();
37
+ async grant(e) {
38
+ if (this.rows.has(e.id))
39
+ return null;
40
+ if ([...this.rows.values()].some((r) => r.idempotencyKey === e.idempotencyKey))
41
+ return null;
42
+ const slot = entActiveSlot(e);
43
+ if (slot !== null &&
44
+ [...this.rows.values()].some((r) => r.activeSlot === slot))
45
+ return null;
46
+ const ts = nowIso();
47
+ const row = {
48
+ ...e,
49
+ sourcePaymentId: e.sourcePaymentId ?? null,
50
+ validUntilMs: e.validUntilMs ?? null,
51
+ activeSlot: slot,
52
+ createdAt: ts,
53
+ updatedAt: ts,
54
+ };
55
+ this.rows.set(row.id, row);
56
+ return row;
57
+ }
58
+ async getById(id) {
59
+ return this.rows.get(id) ?? null;
60
+ }
61
+ async getByIdempotencyKey(key) {
62
+ return ([...this.rows.values()].find((r) => r.idempotencyKey === key) ??
63
+ null);
64
+ }
65
+ async getActive(ownerId, productCode) {
66
+ const slot = `${ownerId}|${productCode}`;
67
+ return ([...this.rows.values()].find((r) => r.activeSlot === slot) ?? null);
68
+ }
69
+ async listByOwner(ownerId, opts) {
70
+ let out = [...this.rows.values()].filter((r) => r.ownerId === ownerId &&
71
+ (opts?.status === undefined || r.status === opts.status) &&
72
+ (opts?.productCode === undefined ||
73
+ r.productCode === opts.productCode));
74
+ out = out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
75
+ if (opts?.limit !== undefined)
76
+ out = out.slice(0, opts.limit);
77
+ return out;
78
+ }
79
+ async listExpiring(nowMs, limit) {
80
+ let out = [...this.rows.values()].filter((r) => r.status === "ACTIVE" &&
81
+ r.validUntilMs != null &&
82
+ r.validUntilMs <= nowMs);
83
+ out = out.sort((a, b) => a.validUntilMs - b.validUntilMs);
84
+ if (limit !== undefined)
85
+ out = out.slice(0, limit);
86
+ return out;
87
+ }
88
+ async applyStatus(id, expectedFrom, to) {
89
+ const row = this.rows.get(id);
90
+ if (!row || row.status !== expectedFrom)
91
+ return null;
92
+ const slot = entActiveSlot({ ...row, status: to });
93
+ if (slot !== null &&
94
+ [...this.rows.values()].some((r) => r.id !== id && r.activeSlot === slot))
95
+ return null;
96
+ const next = {
97
+ ...row,
98
+ status: to,
99
+ activeSlot: slot,
100
+ updatedAt: nowIso(),
101
+ };
102
+ this.rows.set(id, next);
103
+ return next;
104
+ }
105
+ }
106
+ export class InMemoryReputationFactStore {
107
+ rows = new Map();
108
+ async append(f) {
109
+ if (this.rows.has(f.id))
110
+ return null;
111
+ if ([...this.rows.values()].some((r) => r.dedupeKey === f.dedupeKey))
112
+ return null;
113
+ const row = {
114
+ ...f,
115
+ subjectId: f.subjectId ?? null,
116
+ createdAt: nowIso(),
117
+ };
118
+ this.rows.set(row.id, row);
119
+ return row;
120
+ }
121
+ async getById(id) {
122
+ return this.rows.get(id) ?? null;
123
+ }
124
+ async listByActor(actorWallet, opts) {
125
+ let out = [...this.rows.values()].filter((r) => r.actorWallet === actorWallet &&
126
+ (opts?.factType === undefined || r.factType === opts.factType));
127
+ out = out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
128
+ if (opts?.limit !== undefined)
129
+ out = out.slice(0, opts.limit);
130
+ return out;
131
+ }
132
+ async countsByActor(actorWallet) {
133
+ const out = {};
134
+ for (const r of this.rows.values()) {
135
+ if (r.actorWallet !== actorWallet)
136
+ continue;
137
+ out[r.factType] = (out[r.factType] ?? 0) + 1;
138
+ }
139
+ return out;
140
+ }
141
+ }
142
+ function cloneRows(value) {
143
+ if (value === null || typeof value !== "object")
144
+ return value;
145
+ return structuredClone(value);
146
+ }
147
+ function cloneStore(store) {
148
+ return new Proxy(store, {
149
+ get(target, prop, receiver) {
150
+ const value = Reflect.get(target, prop, receiver);
151
+ if (typeof value !== "function")
152
+ return value;
153
+ return async (...args) => cloneRows(await value.apply(target, args));
154
+ },
155
+ });
156
+ }
157
+ export function createInMemoryIdentityStores() {
158
+ let tail = Promise.resolve();
159
+ const stores = {
160
+ actors: cloneStore(new InMemoryActorStore()),
161
+ entitlements: cloneStore(new InMemoryEntitlementStore()),
162
+ facts: cloneStore(new InMemoryReputationFactStore()),
163
+ atomic: async (fn) => {
164
+ const run = tail.then(() => fn(stores));
165
+ tail = run.catch(() => { });
166
+ return run;
167
+ },
168
+ };
169
+ return stores;
170
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.5",
3
+ "version": "0.6.6",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",