@vite-hub/comments 0.0.0 → 0.1.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/LICENSE +201 -0
- package/README.md +243 -0
- package/dist/anchor.d.ts +40 -0
- package/dist/anchor.js +128 -0
- package/dist/client.d.ts +101 -0
- package/dist/client.js +553 -0
- package/dist/console-BIz9t2cO.d.ts +243 -0
- package/dist/database/postgres.d.ts +1011 -0
- package/dist/database/postgres.js +60 -0
- package/dist/database-BSnVrwHn.js +60 -0
- package/dist/database-C-ktS9Do.js +95 -0
- package/dist/database-Cb2xjC1V.d.ts +1096 -0
- package/dist/database.d.ts +104 -0
- package/dist/database.js +3 -0
- package/dist/define-BzW2Ychn.d.ts +46 -0
- package/dist/define-Cbhl6QVJ.js +32 -0
- package/dist/errors-BAQYcy3_.d.ts +89 -0
- package/dist/errors-DeD6wTCl.js +77 -0
- package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
- package/dist/identity-3qtVC4rF.js +34 -0
- package/dist/index-DklG2Etf.d.ts +111 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +5 -0
- package/dist/operations-0B0QTVWX.d.ts +138 -0
- package/dist/operations-NZG5dB8y.js +732 -0
- package/dist/operations.d.ts +7 -0
- package/dist/operations.js +2 -0
- package/dist/overlay/overlay.js +195 -0
- package/dist/page/loader.js +22 -0
- package/dist/page-BtXADR6d.d.ts +21 -0
- package/dist/page-BuroSMXO.js +38 -0
- package/dist/page-tools-shared-D-amu6sx.js +53 -0
- package/dist/plugin-QElKQYkA.js +725 -0
- package/dist/realtime.d.ts +18 -0
- package/dist/realtime.js +48 -0
- package/dist/request-DVc3M_AG.js +14 -0
- package/dist/rpc.d.ts +29 -0
- package/dist/rpc.js +75 -0
- package/dist/runtime/auth.d.ts +6 -0
- package/dist/runtime/auth.js +15 -0
- package/dist/runtime/connect/node.d.ts +1 -0
- package/dist/runtime/connect/node.js +2 -0
- package/dist/runtime/connect.d.ts +1 -0
- package/dist/runtime/connect.js +2 -0
- package/dist/runtime/console.d.ts +5 -0
- package/dist/runtime/console.js +59 -0
- package/dist/runtime/index.d.ts +222 -0
- package/dist/runtime/index.js +665 -0
- package/dist/server-BomGg3Gb.js +63 -0
- package/dist/server.d.ts +94 -0
- package/dist/server.js +326 -0
- package/dist/src-CRTwnaEG.js +1362 -0
- package/dist/testing.d.ts +30 -0
- package/dist/testing.js +175 -0
- package/dist/types-Cj8K7Vx7.d.ts +176 -0
- package/dist/types-Un2dcJWD.d.ts +288 -0
- package/dist/vite.d.ts +304 -0
- package/dist/vite.js +1921 -0
- package/package.json +156 -4
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
|
|
2
|
+
//#region src/operations-core/server.ts
|
|
3
|
+
const key = Symbol.for("vitehub.comments.runtime");
|
|
4
|
+
const scope = globalThis;
|
|
5
|
+
/** Install the runtime of the app. The generated Nitro plugin calls this. The runtime may be a function that builds it on first use. */
|
|
6
|
+
function installComments(runtime) {
|
|
7
|
+
scope[key] = runtime;
|
|
8
|
+
}
|
|
9
|
+
/** The installed runtime, or `COMMENTS_R0010` with status 503. */
|
|
10
|
+
async function commentsRuntime() {
|
|
11
|
+
const installed = scope[key];
|
|
12
|
+
if (!installed) throw Object.assign(commentsErrorDiagnostics.COMMENTS_R0010(), { status: 503 });
|
|
13
|
+
if (installed instanceof Function) {
|
|
14
|
+
const built = await installed();
|
|
15
|
+
scope[key] = built;
|
|
16
|
+
return built;
|
|
17
|
+
}
|
|
18
|
+
return installed;
|
|
19
|
+
}
|
|
20
|
+
function hasCommentsRuntime() {
|
|
21
|
+
return scope[key] !== void 0;
|
|
22
|
+
}
|
|
23
|
+
function toUser(record) {
|
|
24
|
+
const id = typeof record.id === "string" ? record.id : void 0;
|
|
25
|
+
if (!id) return void 0;
|
|
26
|
+
const name = typeof record.name === "string" && record.name ? record.name : void 0;
|
|
27
|
+
const image = typeof record.image === "string" && record.image ? record.image : void 0;
|
|
28
|
+
return {
|
|
29
|
+
id,
|
|
30
|
+
...name ? { name } : {},
|
|
31
|
+
...image ? { image } : {}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** People from a Better Auth instance, through its internal adapter. */
|
|
35
|
+
function createAuthUsers(getAuth) {
|
|
36
|
+
const adapter = async () => (await getAuth().$context).internalAdapter;
|
|
37
|
+
return {
|
|
38
|
+
async byIds(ids) {
|
|
39
|
+
if (!ids.length) return [];
|
|
40
|
+
return (await (await adapter()).listUsers(ids.length, 0, void 0, [{
|
|
41
|
+
field: "id",
|
|
42
|
+
operator: "in",
|
|
43
|
+
value: [...ids]
|
|
44
|
+
}])).flatMap((record) => {
|
|
45
|
+
const person = toUser(record);
|
|
46
|
+
return person ? [{
|
|
47
|
+
...record,
|
|
48
|
+
...person
|
|
49
|
+
}] : [];
|
|
50
|
+
});
|
|
51
|
+
},
|
|
52
|
+
async search(query, limit) {
|
|
53
|
+
return (await (await adapter()).listUsers(limit, 0, void 0, [{
|
|
54
|
+
field: "name",
|
|
55
|
+
operator: "contains",
|
|
56
|
+
value: query,
|
|
57
|
+
mode: "insensitive"
|
|
58
|
+
}])).map(toUser).filter((person) => person !== void 0);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { installComments as i, createAuthUsers as n, hasCommentsRuntime as r, commentsRuntime as t };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { _ as CommentUser, g as CommentThread, h as CommentSubject, n as CommentActor, p as CommentStatus, r as CommentAnchor, u as CommentListQuery } from "./types-Cj8K7Vx7.js";
|
|
2
|
+
import { n as commentMessages, r as commentThreads, t as commentCounters } from "./database-Cb2xjC1V.js";
|
|
3
|
+
import { l as validateCommentsDefinition, o as CommentsDefinition } from "./define-BzW2Ychn.js";
|
|
4
|
+
import { LibSQLDatabase } from "drizzle-orm/libsql";
|
|
5
|
+
//#region src/operations-core/store.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The Drizzle database that the store uses. The store calls `select`, `insert`, `update`, and `delete` (with
|
|
8
|
+
* `onConflictDoNothing()` and `returning()`), which SQLite, libSQL, D1, and Postgres Drizzle databases all offer, and
|
|
9
|
+
* groups writes with `batch()` or `transaction()` when the driver has one. The Postgres tables have the same property
|
|
10
|
+
* names, so one set of queries serves every driver.
|
|
11
|
+
*/
|
|
12
|
+
type CommentsDatabase = LibSQLDatabase<Record<string, never>>;
|
|
13
|
+
/** The tables to query: the ones of the Database schema, so Postgres uses its own. */
|
|
14
|
+
interface CommentsTables {
|
|
15
|
+
commentThreads: typeof commentThreads;
|
|
16
|
+
commentMessages: typeof commentMessages;
|
|
17
|
+
commentCounters: typeof commentCounters;
|
|
18
|
+
}
|
|
19
|
+
interface NewMessage {
|
|
20
|
+
actor?: CommentActor;
|
|
21
|
+
attachments: string[];
|
|
22
|
+
author: CommentUser;
|
|
23
|
+
body: string;
|
|
24
|
+
id: string;
|
|
25
|
+
mentions: string[];
|
|
26
|
+
now: number;
|
|
27
|
+
}
|
|
28
|
+
interface NewThread extends NewMessage {
|
|
29
|
+
anchor: CommentAnchor;
|
|
30
|
+
scope: string;
|
|
31
|
+
subject: CommentSubject;
|
|
32
|
+
threadId: string;
|
|
33
|
+
}
|
|
34
|
+
interface CommentsStore {
|
|
35
|
+
/** Newest first: by `updatedAt`, then `id`. `before` continues after the last thread of an earlier page. */
|
|
36
|
+
list: (query: CommentListQuery & {
|
|
37
|
+
userId?: string;
|
|
38
|
+
}) => Promise<CommentThread[]>;
|
|
39
|
+
getById: (id: string) => Promise<CommentThread | null>;
|
|
40
|
+
getByNumber: (scope: string, n: number) => Promise<CommentThread | null>;
|
|
41
|
+
/**
|
|
42
|
+
* Inserts the thread and its first message together, with the next number of its scope. Several creators at once each
|
|
43
|
+
* get their own number, and a number is never handed out twice.
|
|
44
|
+
*/
|
|
45
|
+
createThread: (input: NewThread) => Promise<CommentThread>;
|
|
46
|
+
addMessage: (threadId: string, input: NewMessage) => Promise<CommentThread>;
|
|
47
|
+
editMessage: (threadId: string, messageId: string, input: {
|
|
48
|
+
body: string;
|
|
49
|
+
mentions: string[];
|
|
50
|
+
now: number;
|
|
51
|
+
}) => Promise<CommentThread>;
|
|
52
|
+
deleteMessage: (threadId: string, messageId: string, now: number) => Promise<CommentThread>;
|
|
53
|
+
/** With `ownerId`, delete only if every message still belongs to that owner at mutation time. */
|
|
54
|
+
deleteThread: (threadId: string, ownerId?: string) => Promise<boolean>;
|
|
55
|
+
setStatus: (threadId: string, status: CommentStatus, by: CommentUser, now: number) => Promise<CommentThread>;
|
|
56
|
+
/**
|
|
57
|
+
* The people that wrote in a thread, for a store without an Auth adapter. Only authors of threads that `canRead`
|
|
58
|
+
* accepts count, and a message without a thread never shows.
|
|
59
|
+
*/
|
|
60
|
+
knownUsers: (query: string, limit: number, canRead: (thread: CommentThread) => Promise<boolean>) => Promise<CommentUser[]>;
|
|
61
|
+
knownUsersByIds: (ids: readonly string[], canRead: (thread: CommentThread) => Promise<boolean>) => Promise<CommentUser[]>;
|
|
62
|
+
}
|
|
63
|
+
export declare function createCommentsStore(database: CommentsDatabase, tables?: CommentsTables): CommentsStore;
|
|
64
|
+
//#endregion
|
|
65
|
+
//#region src/operations-core/server.d.ts
|
|
66
|
+
/** Where mentions find people. */
|
|
67
|
+
export interface CommentsUsers {
|
|
68
|
+
/** People whose name contains `query`. `users()` returns only their `id`, `name`, and `image`. */
|
|
69
|
+
search: (query: string, limit: number) => Promise<CommentUser[]>;
|
|
70
|
+
/** The people with these ids, including fields needed by `authorize`. An id that is not a person is left out. */
|
|
71
|
+
byIds: (ids: readonly string[]) => Promise<CommentUser[]>;
|
|
72
|
+
}
|
|
73
|
+
export interface CommentsRuntime {
|
|
74
|
+
definition: CommentsDefinition;
|
|
75
|
+
store: CommentsStore;
|
|
76
|
+
/** The Auth adapter. Without it, `users()` finds the authors that the store knows. */
|
|
77
|
+
users?: CommentsUsers;
|
|
78
|
+
}
|
|
79
|
+
/** Install the runtime of the app. The generated Nitro plugin calls this. The runtime may be a function that builds it on first use. */
|
|
80
|
+
export declare function installComments(runtime: CommentsRuntime | (() => CommentsRuntime | Promise<CommentsRuntime>)): void;
|
|
81
|
+
/** The installed runtime, or `COMMENTS_R0010` with status 503. */
|
|
82
|
+
export declare function commentsRuntime(): Promise<CommentsRuntime>;
|
|
83
|
+
export declare function hasCommentsRuntime(): boolean;
|
|
84
|
+
interface BetterAuthUsers {
|
|
85
|
+
$context: Promise<{
|
|
86
|
+
internalAdapter: {
|
|
87
|
+
listUsers: (limit?: number, offset?: number, sortBy?: unknown, where?: unknown[]) => Promise<Array<Record<string, unknown>>>;
|
|
88
|
+
};
|
|
89
|
+
}>;
|
|
90
|
+
}
|
|
91
|
+
/** People from a Better Auth instance, through its internal adapter. */
|
|
92
|
+
export declare function createAuthUsers(getAuth: () => BetterAuthUsers): CommentsUsers;
|
|
93
|
+
//#endregion
|
|
94
|
+
export { type CommentsDatabase, type CommentsStore, type CommentsTables, validateCommentsDefinition };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
|
|
2
|
+
import { i as validateCommentsDefinition } from "./define-Cbhl6QVJ.js";
|
|
3
|
+
import { n as commentMessages, r as commentThreads, t as commentCounters } from "./database-BSnVrwHn.js";
|
|
4
|
+
import { i as installComments, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-BomGg3Gb.js";
|
|
5
|
+
import { and, asc, desc, eq, inArray, lt, or, sql } from "drizzle-orm";
|
|
6
|
+
//#region src/operations-core/store.ts
|
|
7
|
+
const chunkSize = 80;
|
|
8
|
+
const allocationAttempts = 12;
|
|
9
|
+
const candidateLimit = 200;
|
|
10
|
+
function chunks(items) {
|
|
11
|
+
const result = [];
|
|
12
|
+
for (let index = 0; index < items.length; index += chunkSize) result.push(items.slice(index, index + chunkSize));
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
function parseJson(value, fallback) {
|
|
16
|
+
if (!value) return fallback;
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(value);
|
|
19
|
+
} catch {
|
|
20
|
+
return fallback;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function user(id, name, image) {
|
|
24
|
+
return {
|
|
25
|
+
id,
|
|
26
|
+
...name ? { name } : {},
|
|
27
|
+
...image ? { image } : {}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function messageOf(row) {
|
|
31
|
+
const actor = parseJson(row.actor, void 0);
|
|
32
|
+
return {
|
|
33
|
+
attachments: parseJson(row.attachments, []),
|
|
34
|
+
author: user(row.authorId, row.authorName, row.authorImage),
|
|
35
|
+
body: row.body,
|
|
36
|
+
createdAt: row.createdAt,
|
|
37
|
+
id: row.id,
|
|
38
|
+
mentions: parseJson(row.mentions, []),
|
|
39
|
+
threadId: row.threadId,
|
|
40
|
+
...actor ? { actor } : {},
|
|
41
|
+
...row.editedAt === null ? {} : { editedAt: row.editedAt }
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function threadOf(row, messages) {
|
|
45
|
+
const actor = parseJson(row.actor, void 0);
|
|
46
|
+
const resolvedBy = parseJson(row.resolvedBy, void 0);
|
|
47
|
+
return {
|
|
48
|
+
anchor: parseJson(row.anchor, { kind: "page" }),
|
|
49
|
+
author: user(row.authorId, row.authorName, row.authorImage),
|
|
50
|
+
createdAt: row.createdAt,
|
|
51
|
+
id: row.id,
|
|
52
|
+
messages,
|
|
53
|
+
n: row.n,
|
|
54
|
+
scope: row.scope,
|
|
55
|
+
status: row.status,
|
|
56
|
+
subject: {
|
|
57
|
+
id: row.subjectId,
|
|
58
|
+
kind: row.subjectKind
|
|
59
|
+
},
|
|
60
|
+
updatedAt: row.updatedAt,
|
|
61
|
+
...actor ? { actor } : {},
|
|
62
|
+
...resolvedBy ? { resolvedBy } : {},
|
|
63
|
+
...row.resolvedAt === null ? {} : { resolvedAt: row.resolvedAt }
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const uniqueCodes = /* @__PURE__ */ new Set([
|
|
67
|
+
"23505",
|
|
68
|
+
"SQLITE_CONSTRAINT_PRIMARYKEY",
|
|
69
|
+
"SQLITE_CONSTRAINT_UNIQUE"
|
|
70
|
+
]);
|
|
71
|
+
const uniqueMessage = /UNIQUE constraint failed|duplicate key value violates unique constraint/i;
|
|
72
|
+
/**
|
|
73
|
+
* A unique index refused the insert. Drizzle wraps the driver error in one whose message carries the statement and its
|
|
74
|
+
* parameters, which come from the user. So only codes decide, and a message counts only when it is the driver's own:
|
|
75
|
+
* the error with no cause below it.
|
|
76
|
+
*/
|
|
77
|
+
function isUniqueViolation(error) {
|
|
78
|
+
for (let current = error, depth = 0; current && depth < 5; depth++) {
|
|
79
|
+
const code = Reflect.get(Object(current), "code");
|
|
80
|
+
if (typeof code === "string" && uniqueCodes.has(code)) return true;
|
|
81
|
+
const cause = Reflect.get(Object(current), "cause");
|
|
82
|
+
if (!cause) return uniqueMessage.test(String(Reflect.get(Object(current), "message") ?? ""));
|
|
83
|
+
current = cause;
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
function escapeLike(value) {
|
|
88
|
+
return value.replaceAll(/[%_\\]/g, "\\$&");
|
|
89
|
+
}
|
|
90
|
+
function createCommentsStore(database, tables = {
|
|
91
|
+
commentCounters,
|
|
92
|
+
commentMessages,
|
|
93
|
+
commentThreads
|
|
94
|
+
}) {
|
|
95
|
+
const { commentCounters: counters, commentMessages: messages, commentThreads: threads } = tables;
|
|
96
|
+
const db = database;
|
|
97
|
+
async function attach(rows) {
|
|
98
|
+
const ids = rows.map((row) => row.id);
|
|
99
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
100
|
+
for (const part of chunks(ids)) {
|
|
101
|
+
const found = await db.select().from(messages).where(inArray(messages.threadId, part)).orderBy(asc(messages.createdAt), asc(messages.id));
|
|
102
|
+
for (const row of found) byThread.set(row.threadId, [...byThread.get(row.threadId) ?? [], messageOf(row)]);
|
|
103
|
+
}
|
|
104
|
+
return rows.map((row) => threadOf(row, byThread.get(row.id) ?? []));
|
|
105
|
+
}
|
|
106
|
+
async function find(id) {
|
|
107
|
+
const [row] = await db.select().from(threads).where(eq(threads.id, id)).limit(1);
|
|
108
|
+
return row ? (await attach([row]))[0] : null;
|
|
109
|
+
}
|
|
110
|
+
async function one(id) {
|
|
111
|
+
const found = await find(id);
|
|
112
|
+
if (!found) throw commentsErrorDiagnostics.COMMENTS_R0002({ id });
|
|
113
|
+
return found;
|
|
114
|
+
}
|
|
115
|
+
const driver = db;
|
|
116
|
+
/** Whether the driver can run several writes as one unit: `batch()` on libSQL and D1, a transaction on Postgres. */
|
|
117
|
+
const groups = typeof driver.batch === "function" || typeof driver.transaction === "function";
|
|
118
|
+
/**
|
|
119
|
+
* Runs the writes together where the driver can. Otherwise they run in order, and the caller orders them so that a
|
|
120
|
+
* failure leaves nothing visible.
|
|
121
|
+
*/
|
|
122
|
+
async function together(build) {
|
|
123
|
+
if (typeof driver.batch === "function") {
|
|
124
|
+
await driver.batch(build(db));
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (typeof driver.transaction === "function") {
|
|
128
|
+
await driver.transaction(async (target) => {
|
|
129
|
+
for (const statement of build(target)) await statement;
|
|
130
|
+
});
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
for (const statement of build(db)) await statement;
|
|
134
|
+
}
|
|
135
|
+
function touching(target, id, now, values = {}) {
|
|
136
|
+
return target.update(threads).set({
|
|
137
|
+
...values,
|
|
138
|
+
updatedAt: sql`case when ${threads.updatedAt} >= ${now} then ${threads.updatedAt} + 1 else ${now} end`
|
|
139
|
+
}).where(eq(threads.id, id));
|
|
140
|
+
}
|
|
141
|
+
function messageRow(threadId, input) {
|
|
142
|
+
return {
|
|
143
|
+
actor: input.actor ? JSON.stringify(input.actor) : null,
|
|
144
|
+
attachments: JSON.stringify(input.attachments),
|
|
145
|
+
authorId: input.author.id,
|
|
146
|
+
authorImage: input.author.image ?? null,
|
|
147
|
+
authorName: input.author.name ?? null,
|
|
148
|
+
body: input.body,
|
|
149
|
+
createdAt: input.now,
|
|
150
|
+
editedAt: null,
|
|
151
|
+
id: input.id,
|
|
152
|
+
mentions: JSON.stringify(input.mentions),
|
|
153
|
+
threadId
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** The next number of a scope. The counter only goes up, so a deleted thread never gives its number away. */
|
|
157
|
+
async function claimNumber(scope) {
|
|
158
|
+
const [existing] = await db.select({ next: counters.next }).from(counters).where(eq(counters.scope, scope)).limit(1);
|
|
159
|
+
if (!existing) {
|
|
160
|
+
const [top] = await db.select({ highest: sql`coalesce(max(${threads.n}), 0)` }).from(threads).where(eq(threads.scope, scope));
|
|
161
|
+
await db.insert(counters).values({
|
|
162
|
+
next: Number(top?.highest ?? 0) + 1,
|
|
163
|
+
scope
|
|
164
|
+
}).onConflictDoNothing();
|
|
165
|
+
}
|
|
166
|
+
const [claimed] = await db.update(counters).set({ next: sql`${counters.next} + 1` }).where(eq(counters.scope, scope)).returning({ next: counters.next });
|
|
167
|
+
if (!claimed) throw commentsErrorDiagnostics.COMMENTS_R0011();
|
|
168
|
+
return Number(claimed.next) - 1;
|
|
169
|
+
}
|
|
170
|
+
function candidateAuthors(where) {
|
|
171
|
+
return db.select({
|
|
172
|
+
createdAt: messages.createdAt,
|
|
173
|
+
messageId: messages.id,
|
|
174
|
+
id: messages.authorId,
|
|
175
|
+
image: messages.authorImage,
|
|
176
|
+
name: messages.authorName,
|
|
177
|
+
threadId: messages.threadId
|
|
178
|
+
}).from(messages).innerJoin(threads, eq(threads.id, messages.threadId)).where(where).orderBy(desc(messages.createdAt), desc(messages.id));
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
async list(query) {
|
|
182
|
+
const subject = query.subject ?? (query.page === void 0 ? void 0 : {
|
|
183
|
+
id: query.page,
|
|
184
|
+
kind: "page"
|
|
185
|
+
});
|
|
186
|
+
const before = query.before;
|
|
187
|
+
const where = [
|
|
188
|
+
...subject ? [eq(threads.subjectKind, subject.kind), eq(threads.subjectId, subject.id)] : [],
|
|
189
|
+
...query.status ? [eq(threads.status, query.status)] : [],
|
|
190
|
+
...query.mine ? [query.userId ? eq(threads.authorId, query.userId) : sql`1 = 0`] : [],
|
|
191
|
+
...query.mentions ? [query.userId ? sql`exists (select 1 from ${messages} where ${messages.threadId} = ${threads.id} and ${messages.mentions} like ${`%${escapeLike(JSON.stringify(query.userId))}%`} escape '\\')` : sql`1 = 0`] : [],
|
|
192
|
+
...before ? [or(lt(threads.updatedAt, before.updatedAt), and(eq(threads.updatedAt, before.updatedAt), lt(threads.id, before.id)))] : []
|
|
193
|
+
];
|
|
194
|
+
const limit = Math.min(Math.max(Math.trunc(query.limit ?? 200), 1), 500);
|
|
195
|
+
return attach(await db.select().from(threads).where(where.length ? and(...where) : void 0).orderBy(desc(threads.updatedAt), desc(threads.id)).limit(limit));
|
|
196
|
+
},
|
|
197
|
+
getById: find,
|
|
198
|
+
async getByNumber(scope, n) {
|
|
199
|
+
const [row] = await db.select().from(threads).where(and(eq(threads.scope, scope), eq(threads.n, n))).limit(1);
|
|
200
|
+
return row ? (await attach([row]))[0] : null;
|
|
201
|
+
},
|
|
202
|
+
async createThread(input) {
|
|
203
|
+
for (let attempt = 0; attempt < allocationAttempts; attempt++) {
|
|
204
|
+
const n = await claimNumber(input.scope);
|
|
205
|
+
const thread = {
|
|
206
|
+
actor: input.actor ? JSON.stringify(input.actor) : null,
|
|
207
|
+
anchor: JSON.stringify(input.anchor),
|
|
208
|
+
authorId: input.author.id,
|
|
209
|
+
authorImage: input.author.image ?? null,
|
|
210
|
+
authorName: input.author.name ?? null,
|
|
211
|
+
createdAt: input.now,
|
|
212
|
+
id: input.threadId,
|
|
213
|
+
n,
|
|
214
|
+
resolvedAt: null,
|
|
215
|
+
resolvedBy: null,
|
|
216
|
+
scope: input.scope,
|
|
217
|
+
status: "open",
|
|
218
|
+
subjectId: input.subject.id,
|
|
219
|
+
subjectKind: input.subject.kind,
|
|
220
|
+
updatedAt: input.now
|
|
221
|
+
};
|
|
222
|
+
try {
|
|
223
|
+
await together((target) => [target.insert(messages).values(messageRow(input.threadId, input)), target.insert(threads).values(thread)]);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (!groups) await db.delete(messages).where(eq(messages.id, input.id)).catch(() => void 0);
|
|
226
|
+
if (isUniqueViolation(error)) continue;
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
return one(input.threadId);
|
|
230
|
+
}
|
|
231
|
+
throw commentsErrorDiagnostics.COMMENTS_R0011();
|
|
232
|
+
},
|
|
233
|
+
async addMessage(threadId, input) {
|
|
234
|
+
await one(threadId);
|
|
235
|
+
await together((target) => [touching(target, threadId, input.now), target.insert(messages).select(sql`select
|
|
236
|
+
${input.id}, ${threadId}, ${input.body}, ${input.author.id}, ${input.author.name ?? null}, ${input.author.image ?? null},
|
|
237
|
+
${input.actor ? JSON.stringify(input.actor) : null}, ${JSON.stringify(input.mentions)}, ${JSON.stringify(input.attachments)},
|
|
238
|
+
(select case when max(${messages.createdAt}) >= ${input.now} then max(${messages.createdAt}) + 1 else ${input.now} end
|
|
239
|
+
from ${messages} where ${messages.threadId} = ${threadId}), null
|
|
240
|
+
from ${threads} where ${threads.id} = ${threadId}`)]);
|
|
241
|
+
return one(threadId);
|
|
242
|
+
},
|
|
243
|
+
async editMessage(threadId, messageId, input) {
|
|
244
|
+
if (!(await one(threadId)).messages.some((message) => message.id === messageId)) throw commentsErrorDiagnostics.COMMENTS_R0003({ messageId });
|
|
245
|
+
await together((target) => [target.update(messages).set({
|
|
246
|
+
body: input.body,
|
|
247
|
+
editedAt: input.now,
|
|
248
|
+
mentions: JSON.stringify(input.mentions)
|
|
249
|
+
}).where(and(eq(messages.id, messageId), eq(messages.threadId, threadId))), touching(target, threadId, input.now)]);
|
|
250
|
+
return one(threadId);
|
|
251
|
+
},
|
|
252
|
+
async deleteMessage(threadId, messageId, now) {
|
|
253
|
+
await together((target) => [target.delete(messages).where(and(eq(messages.id, messageId), eq(messages.threadId, threadId))), touching(target, threadId, now)]);
|
|
254
|
+
return one(threadId);
|
|
255
|
+
},
|
|
256
|
+
async deleteThread(threadId, ownerId) {
|
|
257
|
+
await together((target) => [
|
|
258
|
+
target.update(threads).set({ id: threadId }).where(eq(threads.id, threadId)),
|
|
259
|
+
target.delete(threads).where(and(eq(threads.id, threadId), ownerId === void 0 ? void 0 : sql`not exists (select 1 from ${messages} where ${messages.threadId} = ${threadId} and ${messages.authorId} <> ${ownerId})`)),
|
|
260
|
+
target.delete(messages).where(and(eq(messages.threadId, threadId), sql`not exists (select 1 from ${threads} where ${threads.id} = ${threadId})`))
|
|
261
|
+
]);
|
|
262
|
+
return await find(threadId) === null;
|
|
263
|
+
},
|
|
264
|
+
async setStatus(threadId, status, by, now) {
|
|
265
|
+
await one(threadId);
|
|
266
|
+
await touching(db, threadId, now, status === "resolved" ? {
|
|
267
|
+
resolvedAt: now,
|
|
268
|
+
resolvedBy: JSON.stringify(by),
|
|
269
|
+
status
|
|
270
|
+
} : {
|
|
271
|
+
resolvedAt: null,
|
|
272
|
+
resolvedBy: null,
|
|
273
|
+
status
|
|
274
|
+
});
|
|
275
|
+
return one(threadId);
|
|
276
|
+
},
|
|
277
|
+
async knownUsersByIds(ids, canRead) {
|
|
278
|
+
const seen = /* @__PURE__ */ new Map();
|
|
279
|
+
const readable = /* @__PURE__ */ new Map();
|
|
280
|
+
for (const part of chunks([...new Set(ids)])) {
|
|
281
|
+
const rows = await candidateAuthors(inArray(messages.authorId, part));
|
|
282
|
+
for (const row of rows) {
|
|
283
|
+
if (seen.has(row.id)) continue;
|
|
284
|
+
let allowed = readable.get(row.threadId);
|
|
285
|
+
if (!allowed) {
|
|
286
|
+
allowed = (async () => {
|
|
287
|
+
const found = await find(row.threadId);
|
|
288
|
+
return found ? await canRead(found) : false;
|
|
289
|
+
})();
|
|
290
|
+
readable.set(row.threadId, allowed);
|
|
291
|
+
}
|
|
292
|
+
if (await allowed) seen.set(row.id, user(row.id, row.name, row.image));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return [...seen.values()];
|
|
296
|
+
},
|
|
297
|
+
async knownUsers(query, limit, canRead) {
|
|
298
|
+
const pattern = `%${escapeLike(query.toLowerCase())}%`;
|
|
299
|
+
const matching = sql`lower(coalesce(${messages.authorName}, ${messages.authorId})) like ${pattern} escape '\\'`;
|
|
300
|
+
const seen = /* @__PURE__ */ new Map();
|
|
301
|
+
const readable = /* @__PURE__ */ new Map();
|
|
302
|
+
let before;
|
|
303
|
+
while (seen.size < limit) {
|
|
304
|
+
const rows = await candidateAuthors(and(matching, before ? or(lt(messages.createdAt, before.createdAt), and(eq(messages.createdAt, before.createdAt), lt(messages.id, before.messageId))) : void 0)).limit(candidateLimit);
|
|
305
|
+
for (const row of rows) {
|
|
306
|
+
if (seen.has(row.id)) continue;
|
|
307
|
+
let allowed = readable.get(row.threadId);
|
|
308
|
+
if (!allowed) {
|
|
309
|
+
allowed = (async () => {
|
|
310
|
+
const found = await find(row.threadId);
|
|
311
|
+
return found ? await canRead(found) : false;
|
|
312
|
+
})();
|
|
313
|
+
readable.set(row.threadId, allowed);
|
|
314
|
+
}
|
|
315
|
+
if (await allowed) seen.set(row.id, user(row.id, row.name, row.image));
|
|
316
|
+
if (seen.size >= limit) break;
|
|
317
|
+
}
|
|
318
|
+
if (rows.length < candidateLimit) break;
|
|
319
|
+
before = rows.at(-1);
|
|
320
|
+
}
|
|
321
|
+
return [...seen.values()];
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
export { commentsRuntime, createAuthUsers, createCommentsStore, hasCommentsRuntime, installComments, validateCommentsDefinition };
|