@vite-hub/comments 0.1.0 → 0.3.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 (87) hide show
  1. package/README.md +79 -31
  2. package/dist/anchor.d.ts +7 -4
  3. package/dist/anchor.js +10 -5
  4. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  5. package/dist/client.d.ts +78 -3
  6. package/dist/client.js +198 -13
  7. package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
  8. package/dist/context-BqIsmYP1.js +61 -0
  9. package/dist/database/postgres.d.ts +738 -347
  10. package/dist/database/postgres.js +28 -7
  11. package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
  12. package/dist/database.d.ts +6 -98
  13. package/dist/database.js +2 -3
  14. package/dist/define-43mMR39K.js +89 -0
  15. package/dist/define-B3TF9zzn.d.ts +204 -0
  16. package/dist/errors-4gelGVmK.js +57 -0
  17. package/dist/errors-C6qptPoG.js +135 -0
  18. package/dist/errors-CyQyKAvy.d.ts +185 -0
  19. package/dist/fold-name-B7Zb3-MF.js +7 -0
  20. package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
  21. package/dist/index-DNhy69Wt.d.ts +83 -0
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +196 -5
  24. package/dist/install-BcMPgPk_.js +1154 -0
  25. package/dist/install-W9ghhGoh.d.ts +36 -0
  26. package/dist/installed-B-PfERBU.js +30 -0
  27. package/dist/invariant-D8_xBqmZ.js +22 -0
  28. package/dist/migrate-B0k_0swk.d.ts +54 -0
  29. package/dist/migrate-BDQ8xqUs.js +289 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
  32. package/dist/operations-DMMIfYPW.js +1159 -0
  33. package/dist/operations-GLeOqgMt.d.ts +257 -0
  34. package/dist/operations.d.ts +3 -7
  35. package/dist/operations.js +3 -2
  36. package/dist/overlay/client-DmsSMOzi.js +4 -0
  37. package/dist/overlay/dist-BoHMOFax.js +14 -0
  38. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  39. package/dist/overlay/overlay.js +183 -177
  40. package/dist/page/loader.js +138 -18
  41. package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
  42. package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
  43. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  44. package/dist/path--zk6PEMz.js +18 -0
  45. package/dist/plugin-PS8PMYus.js +74 -0
  46. package/dist/realtime.d.ts +6 -12
  47. package/dist/realtime.js +23 -24
  48. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  49. package/dist/rpc-RKPAusHp.js +153 -0
  50. package/dist/rpc.d.ts +2 -29
  51. package/dist/rpc.js +2 -75
  52. package/dist/runtime/auth.d.ts +5 -3
  53. package/dist/runtime/auth.js +8 -5
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +26 -21
  56. package/dist/runtime/index.d.ts +108 -60
  57. package/dist/runtime/index.js +684 -236
  58. package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
  59. package/dist/server.d.ts +14 -88
  60. package/dist/server.js +7 -326
  61. package/dist/service-CFVm23k7.d.ts +158 -0
  62. package/dist/service-GHhhyQj4.js +609 -0
  63. package/dist/session-DVx-1Tym.d.ts +14 -0
  64. package/dist/session-EkudzUmm.js +503 -0
  65. package/dist/testing.d.ts +1 -1
  66. package/dist/testing.js +14 -2
  67. package/dist/tokens-DSbwkVSy.js +58 -0
  68. package/dist/types-BIS0hCEl.d.ts +124 -0
  69. package/dist/types-CZujrMFd.d.ts +322 -0
  70. package/dist/vite.d.ts +91 -87
  71. package/dist/vite.js +535 -796
  72. package/package.json +24 -27
  73. package/dist/database-BSnVrwHn.js +0 -60
  74. package/dist/database-C-ktS9Do.js +0 -95
  75. package/dist/define-BzW2Ychn.d.ts +0 -46
  76. package/dist/define-Cbhl6QVJ.js +0 -32
  77. package/dist/errors-BAQYcy3_.d.ts +0 -89
  78. package/dist/errors-DeD6wTCl.js +0 -77
  79. package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
  80. package/dist/index-DklG2Etf.d.ts +0 -111
  81. package/dist/operations-NZG5dB8y.js +0 -732
  82. package/dist/page-tools-shared-D-amu6sx.js +0 -53
  83. package/dist/plugin-QElKQYkA.js +0 -725
  84. package/dist/request-DVc3M_AG.js +0 -14
  85. package/dist/src-CRTwnaEG.js +0 -1362
  86. package/dist/types-Cj8K7Vx7.d.ts +0 -176
  87. package/dist/types-Un2dcJWD.d.ts +0 -288
@@ -1,9 +1,12 @@
1
- import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
1
+ import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
2
  //#region src/operations-core/server.ts
3
3
  const key = Symbol.for("vitehub.comments.runtime");
4
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) {
5
+ /**
6
+ * Install the runtime that the comment operations use. `installComments()` calls this; the generated Nitro plugin
7
+ * passes a function that builds the runtime on first use.
8
+ */
9
+ function installCommentsRuntime(runtime) {
7
10
  scope[key] = runtime;
8
11
  }
9
12
  /** The installed runtime, or `COMMENTS_R0010` with status 503. */
@@ -31,9 +34,9 @@ function toUser(record) {
31
34
  ...image ? { image } : {}
32
35
  };
33
36
  }
34
- /** People from a Better Auth instance, through its internal adapter. */
37
+ /** People from a Better Auth instance, through its internal adapter. The generated Nitro plugin passes it when the app has Auth. */
35
38
  function createAuthUsers(getAuth) {
36
- const adapter = async () => (await getAuth().$context).internalAdapter;
39
+ const adapter = async () => (await (await getAuth()).$context).internalAdapter;
37
40
  return {
38
41
  async byIds(ids) {
39
42
  if (!ids.length) return [];
@@ -55,9 +58,15 @@ function createAuthUsers(getAuth) {
55
58
  operator: "contains",
56
59
  value: query,
57
60
  mode: "insensitive"
58
- }])).map(toUser).filter((person) => person !== void 0);
61
+ }])).flatMap((record) => {
62
+ const person = toUser(record);
63
+ return person ? [{
64
+ ...record,
65
+ ...person
66
+ }] : [];
67
+ });
59
68
  }
60
69
  };
61
70
  }
62
71
  //#endregion
63
- export { installComments as i, createAuthUsers as n, hasCommentsRuntime as r, commentsRuntime as t };
72
+ export { installCommentsRuntime as i, createAuthUsers as n, hasCommentsRuntime as r, commentsRuntime as t };
package/dist/server.d.ts CHANGED
@@ -1,94 +1,20 @@
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
1
+ import { d as CommentsPeople, x as validateCommentsDefinition } from "./define-B3TF9zzn.js";
2
+ import { a as maximumCommentBodyLength, c as CommentsTables, i as CommentsRuntime, l as createCommentsStore, n as CommentsAttachmentStore, o as CommentsDatabase, r as CommentsForgeHooks, s as CommentsStore } from "./service-CFVm23k7.js";
3
+ import { a as commentsOperations, i as commentInputSchemas, n as commentActions, r as commentAnchorSchema, t as CommentsCaller } from "./operations-GLeOqgMt.js";
4
+ import { n as createRpcTransport, t as RpcTransportOptions } from "./rpc-HBcWtg0T.js";
5
+ import { n as installComments, t as InstallCommentsOptions } from "./install-W9ghhGoh.js";
6
+ //#region src/operations-core/server.d.ts
7
+ /** Where mentions find people. The same shape as `defineComments({ people })`. */
8
+ export type CommentsUsers = CommentsPeople;
6
9
  /**
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.
10
+ * Install the runtime that the comment operations use. `installComments()` calls this; the generated Nitro plugin
11
+ * passes a function that builds the runtime on first use.
11
12
  */
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;
13
+ export declare function installCommentsRuntime(runtime: CommentsRuntime | (() => CommentsRuntime | Promise<CommentsRuntime>)): void;
81
14
  /** The installed runtime, or `COMMENTS_R0010` with status 503. */
82
15
  export declare function commentsRuntime(): Promise<CommentsRuntime>;
83
16
  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;
17
+ /** People from a Better Auth instance, through its internal adapter. The generated Nitro plugin passes it when the app has Auth. */
18
+ export declare function createAuthUsers(getAuth: () => object | Promise<object>): CommentsPeople;
93
19
  //#endregion
94
- export { type CommentsDatabase, type CommentsStore, type CommentsTables, validateCommentsDefinition };
20
+ export { type CommentsAttachmentStore, CommentsCaller, type CommentsDatabase, type CommentsForgeHooks, type CommentsRuntime, type CommentsStore, type CommentsTables, type InstallCommentsOptions, RpcTransportOptions, commentActions, commentAnchorSchema, commentInputSchemas, commentsOperations, createCommentsStore, createRpcTransport, installComments, maximumCommentBodyLength, validateCommentsDefinition };
package/dist/server.js CHANGED
@@ -1,326 +1,7 @@
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 };
1
+ import { r as createCommentsStore, t as installComments } from "./install-BcMPgPk_.js";
2
+ import { i as commentsOperations, n as commentAnchorSchema, r as commentInputSchemas, t as commentActions } from "./operations-DMMIfYPW.js";
3
+ import { t as createRpcTransport } from "./rpc-RKPAusHp.js";
4
+ import { u as maximumCommentBodyLength } from "./service-GHhhyQj4.js";
5
+ import { c as validateCommentsDefinition } from "./define-43mMR39K.js";
6
+ import { i as installCommentsRuntime, n as createAuthUsers, r as hasCommentsRuntime, t as commentsRuntime } from "./server-D8k-0GXe.js";
7
+ export { commentActions, commentAnchorSchema, commentInputSchemas, commentsOperations, commentsRuntime, createAuthUsers, createCommentsStore, createRpcTransport, hasCommentsRuntime, installComments, installCommentsRuntime, maximumCommentBodyLength, validateCommentsDefinition };
@@ -0,0 +1,158 @@
1
+ import { S as CommentThread, _ as CommentMetadata, h as CommentListQuery, n as CommentActor, r as CommentAnchor, s as CommentContext, w as CommentUser, x as CommentSubject, y as CommentStatus } from "./types-CZujrMFd.js";
2
+ import { d as CommentsPeople, g as CommentsUser, l as CommentsDefinition } from "./define-B3TF9zzn.js";
3
+ import { i as commentThreads, r as commentMessages, t as commentCounters } from "./database-CA1aHKN7.js";
4
+ import "valibot";
5
+ import { LibSQLDatabase } from "drizzle-orm/libsql";
6
+ //#region ../internal/src/runtime/client-rate-limit.d.ts
7
+ /** The part of `checkRateLimit()` from `vite-hub/rate-limit` that a public write calls. */
8
+ type SharedRateLimit = (request: Request, name: string, options: {
9
+ key: string;
10
+ limit: number;
11
+ window: `${number}${"ms" | "s" | "m" | "h" | "d"}`;
12
+ }) => Promise<[unknown, {
13
+ allowed: boolean;
14
+ reason?: string;
15
+ retryAfter?: number;
16
+ cause?: unknown;
17
+ } | undefined]>;
18
+ //#endregion
19
+ //#region src/operations-core/store.d.ts
20
+ /**
21
+ * The Drizzle database that the store uses. The store calls `select`, `insert`, `update`, and `delete` (with
22
+ * `onConflictDoNothing()` and `returning()`), which SQLite, libSQL, D1, and Postgres Drizzle databases all offer, and
23
+ * groups writes with `batch()` or `transaction()` when the driver has one. The Postgres tables have the same property
24
+ * names, so one set of queries serves every driver.
25
+ */
26
+ type CommentsDatabase = LibSQLDatabase;
27
+ /** The tables to query: the ones of the Database schema, so Postgres uses its own. */
28
+ interface CommentsTables {
29
+ commentThreads: typeof commentThreads;
30
+ commentMessages: typeof commentMessages;
31
+ commentCounters: typeof commentCounters;
32
+ }
33
+ interface NewMessage {
34
+ actor?: CommentActor;
35
+ attachments: string[];
36
+ author: CommentUser;
37
+ body: string;
38
+ id: string;
39
+ mentions: string[];
40
+ now: number;
41
+ }
42
+ interface NewThread extends NewMessage {
43
+ anchor: CommentAnchor;
44
+ scope: string;
45
+ subject: CommentSubject;
46
+ threadId: string;
47
+ metadata?: CommentMetadata;
48
+ context?: CommentContext;
49
+ revision?: number;
50
+ /** The retry key. A second thread with the same key in the same scope is never inserted. */
51
+ requestId?: string;
52
+ }
53
+ /** What `list` filters by. `userId` is the signed-in user, for `mine` and `mentions`. */
54
+ type StoreListQuery = CommentListQuery & {
55
+ userId?: string;
56
+ scope?: string;
57
+ };
58
+ interface CommentsStore {
59
+ /** Newest first: by `updatedAt`, then `id`. `before` continues after the last thread of an earlier page. */
60
+ list: (query: StoreListQuery) => Promise<CommentThread[]>;
61
+ getById: (id: string) => Promise<CommentThread | null>;
62
+ getByNumber: (scope: string, n: number) => Promise<CommentThread | null>;
63
+ /** The thread that a `createThread` with this `requestId` stored in the scope. */
64
+ getByRequestId: (scope: string, requestId: string) => Promise<CommentThread | null>;
65
+ /** The thread that holds a message. */
66
+ getByMessage: (messageId: string) => Promise<CommentThread | null>;
67
+ /** Threads listing `key` in a page of matching messages. `cursor` continues after those candidates. */
68
+ getByAttachment: (key: string, cursor?: string) => Promise<{
69
+ threads: CommentThread[];
70
+ cursor?: string;
71
+ }>;
72
+ /**
73
+ * Inserts the thread and its first message together, with the next number of its scope. Several creators at once each
74
+ * get their own number, and a number is never handed out twice. With `requestId`, a thread of the scope that already
75
+ * has that key comes back instead, and nothing is inserted.
76
+ */
77
+ createThread: (input: NewThread) => Promise<CommentThread>;
78
+ /**
79
+ * Adds a message. A resolved thread takes it only with `allowResolved`; otherwise it fails with `COMMENTS_R0016`,
80
+ * checked in the same statement as the insert.
81
+ */
82
+ addMessage: (threadId: string, input: NewMessage, options?: {
83
+ allowResolved?: boolean;
84
+ }) => Promise<CommentThread>;
85
+ editMessage: (threadId: string, messageId: string, input: {
86
+ body: string;
87
+ mentions: string[];
88
+ now: number;
89
+ }) => Promise<CommentThread>;
90
+ deleteMessage: (threadId: string, messageId: string, now: number) => Promise<CommentThread>;
91
+ /** With `ownerId`, delete only if every message still belongs to that owner at mutation time. */
92
+ deleteThread: (threadId: string, ownerId?: string) => Promise<boolean>;
93
+ setStatus: (threadId: string, status: CommentStatus, by: CommentUser, now: number) => Promise<CommentThread>;
94
+ /** Deletes every thread of a scope with its messages, and returns their ids. Numbers of the scope are never reused. */
95
+ deleteScope: (scope: string) => Promise<string[]>;
96
+ /**
97
+ * The people that wrote in a thread, for a store without an Auth adapter. Only authors of threads that `canRead`
98
+ * accepts count, and a message without a thread never shows.
99
+ */
100
+ knownUsers: (query: string, limit: number, canRead: (thread: CommentThread) => Promise<boolean>) => Promise<CommentUser[]>;
101
+ knownUsersByIds: (ids: readonly string[], canRead: (thread: CommentThread) => Promise<boolean>) => Promise<CommentUser[]>;
102
+ }
103
+ declare function createCommentsStore(database: CommentsDatabase, tables?: CommentsTables): CommentsStore;
104
+ //#endregion
105
+ //#region src/operations-core/service.d.ts
106
+ /** Longest message, in characters. */
107
+ declare const maximumCommentBodyLength = 10000;
108
+ /** The parts of a Blob store that attachments use: `blob` of `@vite-hub/blob`. */
109
+ interface CommentsAttachmentStore {
110
+ put: (pathname: string, body: Uint8Array, options: {
111
+ contentType: string;
112
+ }) => Promise<readonly [unknown, unknown]>;
113
+ get?: (pathname: string) => Promise<readonly [unknown, Blob | null | undefined]>;
114
+ }
115
+ /** A file to answer, with the headers that keep a browser from running it. */
116
+ interface CommentsAttachmentBody {
117
+ key: string;
118
+ name: string;
119
+ /** The stored media type when Comments attaches that type, else `application/octet-stream`. */
120
+ type: string;
121
+ size: number;
122
+ /** Whether a browser may show it in the page: images other than SVG. */
123
+ inline: boolean;
124
+ data: Blob;
125
+ }
126
+ /** The pull request sync of `defineComments({ forge })`. */
127
+ interface CommentsForgeHooks {
128
+ /** Starts the sync of a thread after a change. */
129
+ changed: (threadId: string) => void;
130
+ /** The threads with their `forge` link. */
131
+ attach: (threads: CommentThread[]) => Promise<CommentThread[]>;
132
+ }
133
+ /** Everything that the comment operations, the server API, and the overlay API share. */
134
+ interface CommentsRuntime {
135
+ definition: CommentsDefinition;
136
+ /**
137
+ * The app's `identify`, given the server event of a call. With it, the comment operations ask it for the user, as
138
+ * the overlay API does, instead of taking the Console's user.
139
+ */
140
+ identify?: (event: unknown) => Promise<CommentsUser | null>;
141
+ store: CommentsStore;
142
+ /** The Auth adapter. `people` wins over it. Without both, `@` finds the authors that the store knows. */
143
+ users?: CommentsPeople;
144
+ /** Vite's serve command, for the default guest policy. */
145
+ development?: boolean;
146
+ /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
147
+ attachments?: CommentsAttachmentStore;
148
+ forge?: CommentsForgeHooks;
149
+ /**
150
+ * `checkRateLimit` of ViteHub Rate Limit, when it counts in a KV store that every server process shares. Guest writes
151
+ * then count under the Rate Limit name `comments`. Without it, they count in the memory of this process.
152
+ */
153
+ rateLimit?: SharedRateLimit;
154
+ /** Work that runs after the answer, such as `onMention`. `flush()` of the server API waits for it. */
155
+ background?: (task: Promise<unknown>) => void;
156
+ }
157
+ //#endregion
158
+ export { maximumCommentBodyLength as a, CommentsTables as c, CommentsRuntime as i, createCommentsStore as l, CommentsAttachmentStore as n, CommentsDatabase as o, CommentsForgeHooks as r, CommentsStore as s, CommentsAttachmentBody as t, SharedRateLimit as u };