cursedbelt-server 4.26.1 → 4.28.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.
Files changed (68) hide show
  1. package/dist/server/activity/d1.d.ts +70 -0
  2. package/dist/server/activity/d1.js +68 -0
  3. package/dist/server/activity/migrations.d.ts +1 -3
  4. package/dist/server/activity/migrations.js +7 -32
  5. package/dist/server/activity/query.d.ts +123 -0
  6. package/dist/server/activity/query.js +171 -0
  7. package/dist/server/activity/schema.d.ts +13 -0
  8. package/dist/server/activity/schema.js +43 -0
  9. package/dist/server/activity/shareSource.d.ts +1 -1
  10. package/dist/server/activity/shareSource.js +1 -1
  11. package/dist/server/activity/store.d.ts +4 -62
  12. package/dist/server/activity/store.js +14 -145
  13. package/dist/server/engagement/d1.d.ts +67 -0
  14. package/dist/server/engagement/d1.js +81 -0
  15. package/dist/server/engagement/manifestPlaces.d.ts +9 -0
  16. package/dist/server/engagement/manifestPlaces.js +17 -0
  17. package/dist/server/engagement/places.js +2 -18
  18. package/dist/server/notifications/d1.d.ts +80 -0
  19. package/dist/server/notifications/d1.js +226 -0
  20. package/dist/server/notifications/service.d.ts +2 -20
  21. package/dist/server/notifications/types.d.ts +27 -0
  22. package/dist/server/notifications/types.js +1 -0
  23. package/dist/server/sharing/contract.d.ts +94 -0
  24. package/dist/server/sharing/contract.js +3 -0
  25. package/dist/server/sharing/d1.d.ts +77 -0
  26. package/dist/server/sharing/d1.js +309 -0
  27. package/dist/server/sharing/index.d.ts +1 -0
  28. package/dist/server/sharing/migrations.d.ts +1 -4
  29. package/dist/server/sharing/migrations.js +7 -72
  30. package/dist/server/sharing/router.d.ts +8 -4
  31. package/dist/server/sharing/router.js +7 -5
  32. package/dist/server/sharing/schema.d.ts +19 -0
  33. package/dist/server/sharing/schema.js +88 -0
  34. package/dist/server/sharing/sql.js +1 -1
  35. package/dist/server/sharing/statements.d.ts +116 -0
  36. package/dist/server/sharing/statements.js +139 -0
  37. package/dist/server/sharing/store.d.ts +3 -28
  38. package/dist/server/sharing/store.js +32 -105
  39. package/docs/activity.md +7 -0
  40. package/docs/engagement.md +6 -0
  41. package/docs/notifications.md +9 -0
  42. package/package.json +25 -1
  43. package/src/server/activity/d1.spec.ts +169 -0
  44. package/src/server/activity/d1.ts +172 -0
  45. package/src/server/activity/migrations.ts +6 -40
  46. package/src/server/activity/query.ts +283 -0
  47. package/src/server/activity/schema.ts +45 -0
  48. package/src/server/activity/shareSource.ts +2 -2
  49. package/src/server/activity/store.ts +45 -257
  50. package/src/server/engagement/d1.spec.ts +102 -0
  51. package/src/server/engagement/d1.ts +141 -0
  52. package/src/server/engagement/manifestPlaces.ts +24 -0
  53. package/src/server/engagement/places.ts +2 -16
  54. package/src/server/notifications/d1.spec.ts +179 -0
  55. package/src/server/notifications/d1.ts +334 -0
  56. package/src/server/notifications/service.ts +7 -23
  57. package/src/server/notifications/types.ts +29 -0
  58. package/src/server/sharing/contract.ts +109 -0
  59. package/src/server/sharing/d1.spec.ts +242 -0
  60. package/src/server/sharing/d1.ts +430 -0
  61. package/src/server/sharing/index.ts +3 -0
  62. package/src/server/sharing/migrations.ts +12 -85
  63. package/src/server/sharing/router.ts +21 -11
  64. package/src/server/sharing/schema.ts +90 -0
  65. package/src/server/sharing/sql.ts +1 -1
  66. package/src/server/sharing/statements.ts +213 -0
  67. package/src/server/sharing/store.ts +46 -221
  68. package/src/server/telemetryIsWorkerSafe.spec.ts +64 -0
@@ -0,0 +1,334 @@
1
+ /**
2
+ * `cursedbelt-server/notifications/d1` — the notification service over D1, for an app a Worker
3
+ * serves.
4
+ *
5
+ * ── Why it exists ───────────────────────────────────────────────────────────
6
+ * `createNotificationService` builds cwip's `createSqliteNotificationStore` over a synchronous
7
+ * `bun:sqlite` handle; a Worker has neither. `apps/family`'s port to a Worker + D1 (task 393)
8
+ * needs the SAME inbox — the same table, the same coalescing, the same routes — so this is
9
+ * cwip's `NotificationStore` contract implemented over D1, handed to cwip's own
10
+ * `createNotificationCenter`, and mounted by the same `mountNotificationRoutes`. The engine
11
+ * stays cwip's; only the storage changes.
12
+ *
13
+ * ── What is the same, and what is not ─────────────────────────────────────
14
+ * · The table is `createSqliteNotificationStore`'s, column for column and index for index
15
+ * ({@link notificationsDdl}; `./d1.spec.ts` compares the two schemas), so coalescing is
16
+ * still the partial unique index and never only a read.
17
+ * · Every store method runs cwip's statement, bound identically; `./d1.spec.ts` drives both
18
+ * stores through one scenario and compares every result and every row.
19
+ * · 🔴 `hub` is always `null` and `{base}/stream` is never mounted. Live delivery is an
20
+ * in-memory set of open streams, and a Worker isolate cannot share one with the isolate
21
+ * that produced the notification — a stream route that answered 200 and never emitted
22
+ * would be worse than the 404 the client already falls back from. The poll transport is
23
+ * the delivery story here, exactly as it is for `live: false` on the Mac.
24
+ * · 🔴 No DDL runs here, ever. The sync store migrates on construction; on D1 the table is
25
+ * the app's `db/schema.sql`, built from {@link notificationsDdl} (or from an in-memory run
26
+ * of `NOTIFICATION_MIGRATIONS` — the two converge, and the spec proves it).
27
+ *
28
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`
29
+ * (`../telemetryIsWorkerSafe.spec.ts` walks it). Do not import `./service.js`,
30
+ * `./migrations.js` or `./index.js` here.
31
+ *
32
+ * ```ts
33
+ * import { createD1NotificationService } from "cursedbelt-server/notifications/d1";
34
+ *
35
+ * const notifications = createD1NotificationService({ db: createRemoteD1(env.DB) });
36
+ * notifications.mount(app, { authorize: (c) => sso.userOf(c)?.id ?? null });
37
+ * await notifications.center.notify(userId, { type: "share.grant", title: "Shared with you" });
38
+ * ```
39
+ */
40
+ import {
41
+ type AppNotification,
42
+ createNotificationCenter,
43
+ type ListNotificationsQuery,
44
+ type NotificationPage,
45
+ type NotificationStore,
46
+ } from "cwip/notifications";
47
+ import type { D1LikeBindable, D1LikeDatabase } from "../d1/types.js";
48
+ import { mountNotificationRoutes } from "./routes.js";
49
+ import type { NotificationService } from "./types.js";
50
+
51
+ export type { NotificationService, NotificationServiceMountOptions } from "./types.js";
52
+
53
+ /** The default table — the name `createSqliteNotificationStore` and `NOTIFICATION_MIGRATIONS` use. */
54
+ export const D1_NOTIFICATIONS_TABLE = "notifications";
55
+
56
+ const DEFAULT_LIMIT = 50;
57
+
58
+ const assertIdentifier = (name: string): void => {
59
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
60
+ throw new Error(`notifications: invalid table identifier: ${name}`);
61
+ }
62
+ };
63
+
64
+ /**
65
+ * The DDL a D1 schema needs for the notification table — the FINAL shape
66
+ * `createSqliteNotificationStore` migrates any database to (its later `source`/`severity`
67
+ * columns are in the CREATE, as they are in cwip's), with both indexes. Idempotent.
68
+ */
69
+ export function notificationsDdl(table: string = D1_NOTIFICATIONS_TABLE): string[] {
70
+ assertIdentifier(table);
71
+ return [
72
+ `CREATE TABLE IF NOT EXISTS ${table} (
73
+ id TEXT PRIMARY KEY,
74
+ user_id TEXT NOT NULL,
75
+ created_at INTEGER NOT NULL,
76
+ updated_at INTEGER NOT NULL,
77
+ type TEXT NOT NULL,
78
+ source TEXT,
79
+ severity TEXT NOT NULL DEFAULT 'info',
80
+ title TEXT NOT NULL,
81
+ body TEXT,
82
+ link TEXT,
83
+ resource_type TEXT,
84
+ resource_id TEXT,
85
+ actor_id TEXT,
86
+ actor_name TEXT,
87
+ group_key TEXT,
88
+ count INTEGER NOT NULL DEFAULT 1,
89
+ read INTEGER NOT NULL DEFAULT 0,
90
+ done INTEGER NOT NULL DEFAULT 0
91
+ )`,
92
+ `CREATE INDEX IF NOT EXISTS idx_${table}_user ON ${table}(user_id, done, read, created_at)`,
93
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_${table}_group ON ${table}(user_id, group_key)
94
+ WHERE group_key IS NOT NULL AND done = 0`,
95
+ ];
96
+ }
97
+
98
+ /** {@link notificationsDdl} for the default table. */
99
+ export const NOTIFICATIONS_DDL: readonly string[] = notificationsDdl();
100
+
101
+ interface NotificationRow {
102
+ id: string;
103
+ user_id: string;
104
+ created_at: number;
105
+ updated_at: number;
106
+ type: string;
107
+ source: string | null;
108
+ severity: AppNotification["severity"];
109
+ title: string;
110
+ body: string | null;
111
+ link: string | null;
112
+ resource_type: string | null;
113
+ resource_id: string | null;
114
+ actor_id: string | null;
115
+ actor_name: string | null;
116
+ group_key: string | null;
117
+ count: number;
118
+ read: number;
119
+ done: number;
120
+ }
121
+
122
+ /** cwip's `rowToNotification`, verbatim in effect — an absent column is `undefined`, never `null`. */
123
+ const rowToNotification = (row: NotificationRow): AppNotification => ({
124
+ id: row.id,
125
+ userId: row.user_id,
126
+ createdAt: row.created_at,
127
+ updatedAt: row.updated_at,
128
+ type: row.type,
129
+ source: row.source ?? undefined,
130
+ severity: row.severity ?? "info",
131
+ title: row.title,
132
+ body: row.body ?? undefined,
133
+ link: row.link ?? undefined,
134
+ resourceType: row.resource_type ?? undefined,
135
+ resourceId: row.resource_id ?? undefined,
136
+ actorId: row.actor_id ?? undefined,
137
+ actorName: row.actor_name ?? undefined,
138
+ groupKey: row.group_key ?? undefined,
139
+ count: row.count,
140
+ read: !!row.read,
141
+ done: !!row.done,
142
+ });
143
+
144
+ export interface D1NotificationStoreOptions {
145
+ /** Table name override (identifier-validated). Default `notifications`. */
146
+ table?: string;
147
+ }
148
+
149
+ /**
150
+ * cwip's `NotificationStore` over D1 — the same statements as `createSqliteNotificationStore`,
151
+ * awaited. Every method is user-scoped, as the contract requires. Runs no DDL.
152
+ */
153
+ export function createD1NotificationStore(
154
+ db: D1LikeDatabase,
155
+ options: D1NotificationStoreOptions = {},
156
+ ): NotificationStore {
157
+ const table = options.table ?? D1_NOTIFICATIONS_TABLE;
158
+ assertIdentifier(table);
159
+
160
+ const insertSql = `
161
+ INSERT INTO ${table} (id, user_id, created_at, updated_at, type, source, severity, title,
162
+ body, link, resource_type, resource_id, actor_id, actor_name, group_key, count, read, done)
163
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
164
+ `;
165
+ const updateSql = `
166
+ UPDATE ${table} SET updated_at = ?, type = ?, source = ?, severity = ?, title = ?, body = ?,
167
+ link = ?, resource_type = ?, resource_id = ?, actor_id = ?, actor_name = ?, group_key = ?,
168
+ count = ?, read = ?, done = ?
169
+ WHERE id = ? AND user_id = ?
170
+ `;
171
+
172
+ /** 🔴 Every optional becomes `null` and every boolean `0/1` HERE — D1 refuses an
173
+ * `undefined` bind outright, where `bun:sqlite` would have bound NULL without a word. */
174
+ const bindDraftColumns = (n: AppNotification): D1LikeBindable[] => [
175
+ n.type,
176
+ n.source ?? null,
177
+ n.severity,
178
+ n.title,
179
+ n.body ?? null,
180
+ n.link ?? null,
181
+ n.resourceType ?? null,
182
+ n.resourceId ?? null,
183
+ n.actorId ?? null,
184
+ n.actorName ?? null,
185
+ n.groupKey ?? null,
186
+ n.count,
187
+ n.read ? 1 : 0,
188
+ n.done ? 1 : 0,
189
+ ];
190
+
191
+ const one = async (sql: string, ...values: D1LikeBindable[]): Promise<AppNotification | null> => {
192
+ const row = await db
193
+ .prepare(sql)
194
+ .bind(...values)
195
+ .first<NotificationRow>();
196
+ return row ? rowToNotification(row) : null;
197
+ };
198
+ const changes = async (sql: string, ...values: D1LikeBindable[]): Promise<number> =>
199
+ (
200
+ await db
201
+ .prepare(sql)
202
+ .bind(...values)
203
+ .run()
204
+ ).meta.changes;
205
+
206
+ return {
207
+ insert: async (n) => {
208
+ await db
209
+ .prepare(insertSql)
210
+ .bind(n.id, n.userId, n.createdAt, n.updatedAt, ...bindDraftColumns(n))
211
+ .run();
212
+ },
213
+
214
+ update: async (n) => {
215
+ await db
216
+ .prepare(updateSql)
217
+ .bind(n.updatedAt, ...bindDraftColumns(n), n.id, n.userId)
218
+ .run();
219
+ },
220
+
221
+ findOpenByGroup: (userId, groupKey) =>
222
+ one(`SELECT * FROM ${table} WHERE user_id = ? AND group_key = ? AND done = 0 LIMIT 1`, userId, groupKey),
223
+
224
+ get: (userId, id) => one(`SELECT * FROM ${table} WHERE id = ? AND user_id = ?`, id, userId),
225
+
226
+ list: async ({
227
+ userId,
228
+ filter = "all",
229
+ limit = DEFAULT_LIMIT,
230
+ offset = 0,
231
+ }: ListNotificationsQuery): Promise<NotificationPage> => {
232
+ const where =
233
+ filter === "unread"
234
+ ? "user_id = ? AND done = 0 AND read = 0"
235
+ : filter === "done"
236
+ ? "user_id = ? AND done = 1"
237
+ : "user_id = ? AND done = 0";
238
+ // `rowid DESC` breaks a same-millisecond tie by insertion order, as cwip's store does —
239
+ // its comment has the measurement. D1 tables are rowid tables, so it means the same there.
240
+ const { results } = await db
241
+ .prepare(`SELECT * FROM ${table} WHERE ${where} ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?`)
242
+ .bind(userId, limit + 1, offset)
243
+ .all<NotificationRow>();
244
+ return { items: results.slice(0, limit).map(rowToNotification), hasMore: results.length > limit };
245
+ },
246
+
247
+ unreadCount: async (userId) =>
248
+ (await db
249
+ .prepare(`SELECT COUNT(*) AS n FROM ${table} WHERE user_id = ? AND done = 0 AND read = 0`)
250
+ .bind(userId)
251
+ .first<number>("n")) ?? 0,
252
+
253
+ markRead: (userId, id, read) =>
254
+ changes(
255
+ `UPDATE ${table} SET read = ? WHERE id = ? AND user_id = ? AND read != ?`,
256
+ read ? 1 : 0,
257
+ id,
258
+ userId,
259
+ read ? 1 : 0,
260
+ ),
261
+
262
+ markAllRead: (userId) =>
263
+ changes(`UPDATE ${table} SET read = 1 WHERE user_id = ? AND done = 0 AND read = 0`, userId),
264
+
265
+ setDone: (userId, id, done) =>
266
+ changes(
267
+ `UPDATE ${table} SET done = ?, read = CASE WHEN ? = 1 THEN 1 ELSE read END
268
+ WHERE id = ? AND user_id = ? AND done != ?`,
269
+ done ? 1 : 0,
270
+ done ? 1 : 0,
271
+ id,
272
+ userId,
273
+ done ? 1 : 0,
274
+ ),
275
+
276
+ doneAll: (userId) => changes(`UPDATE ${table} SET done = 1, read = 1 WHERE user_id = ? AND done = 0`, userId),
277
+
278
+ remove: (userId, id) => changes(`DELETE FROM ${table} WHERE id = ? AND user_id = ?`, id, userId),
279
+
280
+ pruneDone: (olderThanMs) => changes(`DELETE FROM ${table} WHERE done = 1 AND updated_at < ?`, olderThanMs),
281
+ };
282
+ }
283
+
284
+ export interface CreateD1NotificationServiceOptions {
285
+ /** The app's D1 handle — `createRemoteD1(env.DB)` on a Worker, `createLocalD1(sqlite)` in a test. */
286
+ db: D1LikeDatabase;
287
+ /** Table name override (identifier-validated). */
288
+ table?: string;
289
+ /** Resolve a role audience (`notifyAudience({ role })`) to user ids. */
290
+ resolveRole?: (role: string) => Promise<string[]>;
291
+ /** Producer-path failures land here. Defaults to stderr. */
292
+ onError?: (error: unknown, context: string) => void;
293
+ /** Test seams, forwarded to the center. */
294
+ now?: () => number;
295
+ newId?: () => string;
296
+ }
297
+
298
+ /**
299
+ * The whole server half over D1 — `createNotificationService`'s shape, with `hub: null`.
300
+ * `mount` hangs the same routes on the app, minus `{base}/stream` (see the header).
301
+ */
302
+ export function createD1NotificationService(options: CreateD1NotificationServiceOptions): NotificationService {
303
+ const onError =
304
+ options.onError ??
305
+ ((error: unknown, context: string) =>
306
+ console.error(`[notifications] ${context}:`, error instanceof Error ? error.message : error));
307
+
308
+ const store = createD1NotificationStore(options.db, { table: options.table });
309
+
310
+ const center = createNotificationCenter({
311
+ store,
312
+ resolveRole: options.resolveRole,
313
+ now: options.now,
314
+ newId: options.newId,
315
+ onError,
316
+ });
317
+
318
+ return {
319
+ center,
320
+ store,
321
+ hub: null,
322
+ mount(app, mountOptions) {
323
+ mountNotificationRoutes(app, {
324
+ center,
325
+ authorize: mountOptions.authorize,
326
+ basePath: mountOptions.basePath,
327
+ maxLimit: mountOptions.maxLimit,
328
+ });
329
+ },
330
+ close() {
331
+ // Nothing to close: there are no live streams on D1.
332
+ },
333
+ };
334
+ }
@@ -16,13 +16,16 @@ import type { Database } from "bun:sqlite";
16
16
  import {
17
17
  createNotificationCenter,
18
18
  createSqliteNotificationStore,
19
- type NotificationCenter,
20
19
  type NotificationDb,
21
- type NotificationStore,
22
20
  } from "cwip/notifications";
23
- import type { Context, Hono } from "hono";
24
- import { createNotificationHub, type NotificationHub } from "./hub.js";
21
+ import { createNotificationHub } from "./hub.js";
25
22
  import { mountNotificationRoutes } from "./routes.js";
23
+ import type { NotificationService } from "./types.js";
24
+
25
+ // The service's SHAPE has no driver in it, so `./d1.ts` (which runs on `workerd`) returns the
26
+ // same `NotificationService` without reaching this file. Re-exported so
27
+ // `cursedbelt-server/notifications` is unchanged.
28
+ export type { NotificationService, NotificationServiceMountOptions } from "./types.js";
26
29
 
27
30
  export interface CreateNotificationServiceOptions {
28
31
  /** The app's own database — the table lands beside its rows. */
@@ -44,25 +47,6 @@ export interface CreateNotificationServiceOptions {
44
47
  newId?: () => string;
45
48
  }
46
49
 
47
- export interface NotificationServiceMountOptions {
48
- /** Resolve the caller to a user id, or null to refuse. */
49
- authorize: (c: Context) => string | null | Promise<string | null>;
50
- /** Path prefix. Default `/api/notifications`. */
51
- basePath?: string;
52
- /** Largest page a caller may ask for. Default 200. */
53
- maxLimit?: number;
54
- }
55
-
56
- export interface NotificationService {
57
- readonly center: NotificationCenter;
58
- readonly store: NotificationStore;
59
- /** Null when `live: false` — there is then nothing to stream. */
60
- readonly hub: NotificationHub | null;
61
- mount(app: Hono, options: NotificationServiceMountOptions): void;
62
- /** Drop live subscribers (shutdown, tests). Safe to call with no hub. */
63
- close(): void;
64
- }
65
-
66
50
  export function createNotificationService(
67
51
  options: CreateNotificationServiceOptions,
68
52
  ): NotificationService {
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The notification service's shape with no driver attached — what `createNotificationService`
3
+ * (`bun:sqlite`) and `createD1NotificationService` (D1, `./d1.ts`) both return. It lives apart
4
+ * from `./service.ts` so the D1 half, which runs on `workerd`, never reaches a module that
5
+ * names `bun:sqlite`, not even as a type.
6
+ */
7
+ import type { NotificationCenter, NotificationStore } from "cwip/notifications";
8
+ import type { Context, Hono } from "hono";
9
+ import type { NotificationHub } from "./hub.js";
10
+
11
+ export interface NotificationServiceMountOptions {
12
+ /** Resolve the caller to a user id, or null to refuse. */
13
+ authorize: (c: Context) => string | null | Promise<string | null>;
14
+ /** Path prefix. Default `/api/notifications`. */
15
+ basePath?: string;
16
+ /** Largest page a caller may ask for. Default 200. */
17
+ maxLimit?: number;
18
+ }
19
+
20
+ export interface NotificationService {
21
+ readonly center: NotificationCenter;
22
+ readonly store: NotificationStore;
23
+ /** Null when `live: false`, and always on D1 (`./d1.ts`) — there is then nothing to stream,
24
+ * and the client's poll transport is the whole delivery story. */
25
+ readonly hub: NotificationHub | null;
26
+ mount(app: Hono, options: NotificationServiceMountOptions): void;
27
+ /** Drop live subscribers (shutdown, tests). Safe to call with no hub. */
28
+ close(): void;
29
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The store's contract with no driver attached: the input shapes both stores take, the
3
+ * {@link AsyncShareStore} a D1-backed store satisfies, and the two subject helpers.
4
+ *
5
+ * It lives apart from `./store.ts` so that `./d1.ts` — which runs on `workerd` — and its
6
+ * declaration file never reach a module that names `bun:sqlite`, not even as a type. The
7
+ * sync store re-exports everything here, so `cursedbelt-server/sharing` is unchanged.
8
+ */
9
+ import type {
10
+ ShareAccess,
11
+ ShareEvent,
12
+ ShareGrant,
13
+ ShareGroup,
14
+ ShareGroupMember,
15
+ ShareLevel,
16
+ ShareSubject,
17
+ ShareViewer,
18
+ } from "cursedbelt-core/sharing/model";
19
+
20
+ /** Shorthand for the common subject. `group(id)` is its sibling. */
21
+ export const user = (id: string): ShareSubject => ({ type: "user", id });
22
+ export const group = (id: string): ShareSubject => ({ type: "group", id });
23
+
24
+ /** A resource within the store's own app — the `app` half is supplied by the
25
+ * store, so a caller cannot mistakenly write a grant into another app's rows. */
26
+ export interface ShareTarget {
27
+ kind: string;
28
+ id: string;
29
+ }
30
+
31
+ export interface GrantInput extends ShareTarget {
32
+ subject: ShareSubject;
33
+ level: ShareLevel;
34
+ grantedBy: string;
35
+ note?: string;
36
+ }
37
+
38
+ export interface RevokeInput extends ShareTarget {
39
+ subject: ShareSubject;
40
+ revokedBy: string;
41
+ note?: string;
42
+ }
43
+
44
+ export interface ShareEventQuery {
45
+ kind?: string;
46
+ id?: string;
47
+ subject?: ShareSubject;
48
+ /** Newest first, capped. Default 200 — a panel shows a page, and an unbounded
49
+ * audit read on a busy resource is the query that times out in production. */
50
+ limit?: number;
51
+ }
52
+
53
+ /** What `sharedSql` takes — the store supplies `app`. */
54
+ export interface SharedSqlInput {
55
+ kind: string;
56
+ subjectId: string;
57
+ column: string;
58
+ atLeast?: ShareLevel;
59
+ }
60
+
61
+ /**
62
+ * The share store over an ASYNC database — `createD1ShareStore` in
63
+ * `cursedbelt-server/sharing/d1`.
64
+ *
65
+ * The same methods as the sync `ShareStore`, with the same names, arguments and meaning;
66
+ * every method that touches the database resolves instead of returning. `sharedSql` stays
67
+ * synchronous because it touches nothing: it emits the SAME fragment the sync store does, for
68
+ * an app to embed in its own D1 queries. `sharing/d1.spec.ts` checks the two stores expose
69
+ * exactly the same method names, so neither can grow a verb the other lacks.
70
+ */
71
+ export interface AsyncShareStore {
72
+ /** The app this store speaks for. */
73
+ readonly app: string;
74
+ grant(input: GrantInput): Promise<ShareGrant>;
75
+ revoke(input: RevokeInput): Promise<ShareLevel | null>;
76
+ revokeResource(target: ShareTarget, revokedBy: string): Promise<number>;
77
+ revokeSubject(subject: ShareSubject, revokedBy: string): Promise<number>;
78
+ listForResource(target: ShareTarget): Promise<ShareGrant[]>;
79
+ listForSubject(subject: ShareSubject): Promise<ShareGrant[]>;
80
+ accessFor(target: ShareTarget, viewer: ShareViewer): Promise<ShareAccess>;
81
+ resourceIdsFor(kind: string, viewer: ShareViewer, atLeast?: ShareLevel): Promise<string[]>;
82
+ sharedSql(input: SharedSqlInput): string;
83
+ createGroup(input: { id: string; name: string; createdBy: string; note?: string }): Promise<ShareGroup>;
84
+ renameGroup(id: string, name: string, actor: string): Promise<void>;
85
+ deleteGroup(id: string, actor: string): Promise<void>;
86
+ listGroups(): Promise<ShareGroup[]>;
87
+ addGroupMember(groupId: string, subjectId: string, actor: string): Promise<void>;
88
+ removeGroupMember(groupId: string, subjectId: string, actor: string): Promise<void>;
89
+ listGroupMembers(groupId: string): Promise<ShareGroupMember[]>;
90
+ groupIdsFor(subjectId: string): Promise<string[]>;
91
+ events(query?: ShareEventQuery): Promise<ShareEvent[]>;
92
+ }
93
+
94
+ /**
95
+ * A value that may or may not be a promise — what a consumer holding EITHER store gets back
96
+ * from a call, and what it can always `await`.
97
+ */
98
+ export type Awaitable<T> = T | Promise<T>;
99
+
100
+ /**
101
+ * Either store, as a consumer that works over both sees it: every method's result is
102
+ * {@link Awaitable}. `mountShareRoutes` takes this, and awaits every call — awaiting a
103
+ * synchronous value is a no-op, so the sync store's behaviour through it is unchanged.
104
+ */
105
+ export type AwaitableShareStore = {
106
+ readonly [K in keyof AsyncShareStore]: AsyncShareStore[K] extends (...args: infer A) => Promise<infer R>
107
+ ? (...args: A) => Awaitable<R>
108
+ : AsyncShareStore[K];
109
+ };