@vite-hub/comments 0.0.0-stage → 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 +242 -2
- 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 -3
|
@@ -0,0 +1,1362 @@
|
|
|
1
|
+
import { r as defineComments$1 } from "./define-Cbhl6QVJ.js";
|
|
2
|
+
import { t as commentsSchema } from "./database-C-ktS9Do.js";
|
|
3
|
+
import { n as commentsPageScope, o as normalizeCommentPage } from "./page-BuroSMXO.js";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
import { and, desc, eq, exists, inArray, isNotNull, isNull, like, sql } from "drizzle-orm";
|
|
6
|
+
import { defineErrors } from "@vite-hub/runtime";
|
|
7
|
+
import { forgeEnv, githubAppCredentials, readForgeEnv, readGitHubAppPrivateKey } from "@vite-hub/forge";
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
//#region src/errors.ts
|
|
10
|
+
const commentsErrors = /*#__PURE__*/ defineErrors({
|
|
11
|
+
docs: "https://vitehub.dev/docs/comments/limits-and-errors",
|
|
12
|
+
codes: {
|
|
13
|
+
COMMENTS_NOT_INSTALLED: {
|
|
14
|
+
why: "The Comments runtime has no Database yet. ViteHub installs it from `server/comments.ts` when the server starts.",
|
|
15
|
+
fix: "Call the method from a server route or a Nitro plugin of the app, not at import time, and enable a Database with `vitehub({ database: true })`."
|
|
16
|
+
},
|
|
17
|
+
COMMENTS_NOT_FOUND: {
|
|
18
|
+
why: ({ id }) => `No comment thread or comment has the id ${JSON.stringify(id)}.`,
|
|
19
|
+
fix: "List the threads with `comments.list()` and use one of their ids. A deleted thread does not come back."
|
|
20
|
+
},
|
|
21
|
+
COMMENTS_INVALID_INPUT: {
|
|
22
|
+
why: ({ issue }) => `The comment input is not valid: ${issue}`,
|
|
23
|
+
fix: "Send a page path that starts with `/`, an anchor from the overlay, and a body of 1 to 4,000 characters."
|
|
24
|
+
},
|
|
25
|
+
COMMENTS_FORBIDDEN: {
|
|
26
|
+
why: ({ action }) => `The \`authorize\` policy of \`defineComments()\` denied \`${action}\` for this user.`,
|
|
27
|
+
fix: "Sign in as a user that the policy allows, or change `authorize` in `server/comments.ts`."
|
|
28
|
+
},
|
|
29
|
+
COMMENTS_RESOLVED: {
|
|
30
|
+
why: "The thread is resolved, so it takes no new replies.",
|
|
31
|
+
fix: "Reopen the thread with `comments.reopen(id)` first."
|
|
32
|
+
},
|
|
33
|
+
COMMENTS_CONTENT_MISSING: {
|
|
34
|
+
why: "Inline edits need Content, and the app has no `server/content.ts` with document collections.",
|
|
35
|
+
fix: "Define collections with `defineContent()` in `server/content.ts`, and mark rendered fields with `contentField()`."
|
|
36
|
+
},
|
|
37
|
+
COMMENTS_FIELD_INVALID: {
|
|
38
|
+
why: ({ field }) => `${JSON.stringify(field)} is not a Content field address, or its collection, document, or field does not exist.`,
|
|
39
|
+
fix: "Write the attribute with `contentField(collection, id, field)` from `vite-hub/content/client`, so the address matches a collection of `server/content.ts`."
|
|
40
|
+
},
|
|
41
|
+
COMMENTS_FIELD_NOT_EDITABLE: {
|
|
42
|
+
why: ({ field }) => `The draft value of ${JSON.stringify(field)} is not a string, so it cannot be edited as text on the page.`,
|
|
43
|
+
fix: "Edit the field in the Console Content editor."
|
|
44
|
+
},
|
|
45
|
+
COMMENTS_FIELD_FORBIDDEN: {
|
|
46
|
+
why: ({ field }) => `\`content.can()\` denied \`write\` on the document of ${JSON.stringify(field)} for this user.`,
|
|
47
|
+
fix: "Sign in as a user that the `authorize` policy of `defineContent()` lets write the collection."
|
|
48
|
+
},
|
|
49
|
+
COMMENTS_FIELD_CONFLICT: {
|
|
50
|
+
why: ({ field }) => `The document of ${JSON.stringify(field)} changed after the page read it.`,
|
|
51
|
+
fix: "Open the field again to read the current draft, then repeat the edit."
|
|
52
|
+
},
|
|
53
|
+
COMMENTS_FIELD_LOCKED: {
|
|
54
|
+
why: ({ holder }) => `${holder} holds the edit lease of this document in the Console.`,
|
|
55
|
+
fix: "Wait until they close the document, or edit it together with them in the Console."
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/schema.ts
|
|
61
|
+
const thousandths = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(1e3));
|
|
62
|
+
const anchorSchema = v.object({
|
|
63
|
+
field: v.optional(v.pipe(v.string(), v.maxLength(512))),
|
|
64
|
+
selector: v.pipe(v.string(), v.maxLength(2048)),
|
|
65
|
+
label: v.pipe(v.string(), v.maxLength(200)),
|
|
66
|
+
x: thousandths,
|
|
67
|
+
y: thousandths,
|
|
68
|
+
page: v.object({
|
|
69
|
+
x: thousandths,
|
|
70
|
+
y: v.pipe(v.number(), v.minValue(0), v.maxValue(1e6))
|
|
71
|
+
}),
|
|
72
|
+
viewport: v.object({ width: v.pipe(v.number(), v.minValue(0), v.maxValue(1e5)) })
|
|
73
|
+
});
|
|
74
|
+
const short = (max) => v.pipe(v.string(), v.maxLength(max));
|
|
75
|
+
const size = v.pipe(v.number(), v.minValue(0), v.maxValue(1e5));
|
|
76
|
+
const componentSchema = v.object({
|
|
77
|
+
name: short(128),
|
|
78
|
+
files: v.optional(v.pipe(v.array(short(512)), v.maxLength(8)))
|
|
79
|
+
});
|
|
80
|
+
const contextSchema = v.object({
|
|
81
|
+
url: short(2048),
|
|
82
|
+
title: v.optional(short(256)),
|
|
83
|
+
route: v.optional(short(256)),
|
|
84
|
+
element: v.optional(v.object({
|
|
85
|
+
tag: short(64),
|
|
86
|
+
id: v.optional(short(128)),
|
|
87
|
+
testId: v.optional(short(128)),
|
|
88
|
+
role: v.optional(short(64)),
|
|
89
|
+
name: v.optional(short(120)),
|
|
90
|
+
classes: v.optional(v.pipe(v.array(short(64)), v.maxLength(8)))
|
|
91
|
+
})),
|
|
92
|
+
components: v.optional(v.pipe(v.array(componentSchema), v.maxLength(12))),
|
|
93
|
+
environment: v.optional(v.object({
|
|
94
|
+
viewport: v.object({
|
|
95
|
+
width: size,
|
|
96
|
+
height: size
|
|
97
|
+
}),
|
|
98
|
+
devicePixelRatio: v.pipe(v.number(), v.minValue(0), v.maxValue(16)),
|
|
99
|
+
userAgent: short(512),
|
|
100
|
+
language: v.optional(short(64)),
|
|
101
|
+
colorScheme: v.optional(v.picklist(["light", "dark"])),
|
|
102
|
+
timeZone: v.optional(short(64))
|
|
103
|
+
})),
|
|
104
|
+
build: v.optional(v.object({
|
|
105
|
+
commit: v.optional(short(64)),
|
|
106
|
+
branch: v.optional(short(256)),
|
|
107
|
+
repository: v.optional(short(256)),
|
|
108
|
+
pullRequest: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1)))
|
|
109
|
+
}))
|
|
110
|
+
});
|
|
111
|
+
const metadataValue = v.union([
|
|
112
|
+
v.pipe(v.string(), v.maxLength(4e3)),
|
|
113
|
+
v.number(),
|
|
114
|
+
v.boolean(),
|
|
115
|
+
v.null()
|
|
116
|
+
]);
|
|
117
|
+
const metadataSchema = v.pipe(v.record(v.pipe(v.string(), v.minLength(1), v.maxLength(64)), metadataValue), v.check((value) => Object.keys(value).length <= 50, "Keep at most 50 metadata fields."));
|
|
118
|
+
const scopeSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(256));
|
|
119
|
+
const bodySchema = v.pipe(v.string(), v.trim(), v.minLength(1, "The comment is empty."), v.maxLength(4e3, "Keep a comment under 4,000 characters."));
|
|
120
|
+
const mentionsSchema = v.pipe(v.optional(v.array(v.object({
|
|
121
|
+
id: v.pipe(v.string(), v.minLength(1), v.maxLength(256)),
|
|
122
|
+
name: v.pipe(v.string(), v.minLength(1), v.maxLength(256))
|
|
123
|
+
})), []), v.maxLength(20, "Mention at most 20 people in one comment."));
|
|
124
|
+
const authorSchema = v.object({
|
|
125
|
+
id: v.pipe(v.string(), v.minLength(1), v.maxLength(256)),
|
|
126
|
+
name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(256)),
|
|
127
|
+
image: v.optional(v.pipe(v.string(), v.maxLength(2048))),
|
|
128
|
+
guest: v.optional(v.boolean())
|
|
129
|
+
});
|
|
130
|
+
const pageSchema = v.pipe(v.string(), v.startsWith("/", "A page starts with `/`."), v.maxLength(1024));
|
|
131
|
+
const createThreadSchema = v.object({
|
|
132
|
+
scope: v.optional(scopeSchema, "pages"),
|
|
133
|
+
page: pageSchema,
|
|
134
|
+
anchor: v.optional(anchorSchema),
|
|
135
|
+
metadata: v.optional(metadataSchema),
|
|
136
|
+
context: v.optional(contextSchema),
|
|
137
|
+
body: bodySchema,
|
|
138
|
+
author: authorSchema,
|
|
139
|
+
mentions: mentionsSchema
|
|
140
|
+
});
|
|
141
|
+
const editSchema = v.object({
|
|
142
|
+
body: bodySchema,
|
|
143
|
+
mentions: mentionsSchema
|
|
144
|
+
});
|
|
145
|
+
const replySchema = v.object({
|
|
146
|
+
body: bodySchema,
|
|
147
|
+
author: authorSchema,
|
|
148
|
+
mentions: mentionsSchema
|
|
149
|
+
});
|
|
150
|
+
/** The first issue as one sentence, for `COMMENTS_INVALID_INPUT`. */
|
|
151
|
+
function describeIssue(issues) {
|
|
152
|
+
const issue = issues[0];
|
|
153
|
+
if (!issue) return "unknown issue.";
|
|
154
|
+
const path = issue.path?.map((item) => String(item.key)).join(".");
|
|
155
|
+
return path ? `${path}: ${issue.message}` : issue.message;
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/store.ts
|
|
159
|
+
const { vitehubCommentThreads: threads, vitehubComments: comments, vitehubCommentScopeCounters: counters } = commentsSchema;
|
|
160
|
+
function json(value) {
|
|
161
|
+
return value === null ? null : JSON.parse(value);
|
|
162
|
+
}
|
|
163
|
+
function iso(value) {
|
|
164
|
+
return new Date(value).toISOString();
|
|
165
|
+
}
|
|
166
|
+
function toComment(row) {
|
|
167
|
+
return {
|
|
168
|
+
id: row.id,
|
|
169
|
+
threadId: row.threadId,
|
|
170
|
+
body: row.body,
|
|
171
|
+
mentions: json(row.mentions) ?? [],
|
|
172
|
+
author: json(row.author),
|
|
173
|
+
createdAt: iso(row.createdAt),
|
|
174
|
+
editedAt: row.editedAt === null ? null : iso(row.editedAt)
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function toThread(row, rows) {
|
|
178
|
+
return {
|
|
179
|
+
id: row.id,
|
|
180
|
+
scope: row.scope,
|
|
181
|
+
number: row.number,
|
|
182
|
+
page: row.page,
|
|
183
|
+
anchor: json(row.anchor),
|
|
184
|
+
metadata: json(row.metadata),
|
|
185
|
+
context: json(row.context),
|
|
186
|
+
status: row.status,
|
|
187
|
+
createdBy: json(row.createdBy),
|
|
188
|
+
resolvedBy: json(row.resolvedBy),
|
|
189
|
+
resolvedAt: row.resolvedAt === null ? null : iso(row.resolvedAt),
|
|
190
|
+
createdAt: iso(row.createdAt),
|
|
191
|
+
updatedAt: iso(row.updatedAt),
|
|
192
|
+
comments: rows.map(toComment)
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** Comment threads in one Database. Each write is one atomic batch or statement. */
|
|
196
|
+
function createCommentsStore(database) {
|
|
197
|
+
async function withComments(rows) {
|
|
198
|
+
if (!rows.length) return [];
|
|
199
|
+
const commentRows = await database.select().from(comments).where(inArray(comments.threadId, rows.map((row) => row.id))).orderBy(comments.createdAt);
|
|
200
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
201
|
+
for (const row of commentRows) {
|
|
202
|
+
const list = byThread.get(row.threadId) ?? [];
|
|
203
|
+
list.push(row);
|
|
204
|
+
byThread.set(row.threadId, list);
|
|
205
|
+
}
|
|
206
|
+
return rows.map((row) => toThread(row, byThread.get(row.id) ?? []));
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
async list({ scope, page, status, limit }) {
|
|
210
|
+
const where = and(scope === void 0 ? void 0 : eq(threads.scope, scope), page === void 0 ? void 0 : eq(threads.page, page), status === void 0 ? void 0 : eq(threads.status, status));
|
|
211
|
+
return await withComments(await database.select().from(threads).where(where).orderBy(desc(threads.updatedAt)).limit(limit));
|
|
212
|
+
},
|
|
213
|
+
async get(id) {
|
|
214
|
+
const [thread] = await withComments(await database.select().from(threads).where(eq(threads.id, id)).limit(1));
|
|
215
|
+
return thread;
|
|
216
|
+
},
|
|
217
|
+
async getByNumber(scope, number) {
|
|
218
|
+
const [thread] = await withComments(await database.select().from(threads).where(and(eq(threads.scope, scope), eq(threads.number, number))).limit(1));
|
|
219
|
+
return thread;
|
|
220
|
+
},
|
|
221
|
+
async threadOf(commentId) {
|
|
222
|
+
const [row] = await database.select({ threadId: comments.threadId }).from(comments).where(eq(comments.id, commentId)).limit(1);
|
|
223
|
+
return row?.threadId;
|
|
224
|
+
},
|
|
225
|
+
async create({ scope, page, anchor, context, metadata, body, author, mentions }) {
|
|
226
|
+
const now = Date.now();
|
|
227
|
+
const thread = {
|
|
228
|
+
id: crypto.randomUUID(),
|
|
229
|
+
scope,
|
|
230
|
+
number: 0,
|
|
231
|
+
page,
|
|
232
|
+
anchor: JSON.stringify(anchor ?? null),
|
|
233
|
+
context: context ? JSON.stringify(context) : null,
|
|
234
|
+
metadata: metadata ? JSON.stringify(metadata) : null,
|
|
235
|
+
status: "open",
|
|
236
|
+
createdBy: JSON.stringify(author),
|
|
237
|
+
resolvedBy: null,
|
|
238
|
+
resolvedAt: null,
|
|
239
|
+
createdAt: now,
|
|
240
|
+
updatedAt: now
|
|
241
|
+
};
|
|
242
|
+
const comment = {
|
|
243
|
+
id: crypto.randomUUID(),
|
|
244
|
+
threadId: thread.id,
|
|
245
|
+
body,
|
|
246
|
+
mentions: JSON.stringify(mentions),
|
|
247
|
+
author: JSON.stringify(author),
|
|
248
|
+
createdAt: now,
|
|
249
|
+
editedAt: null
|
|
250
|
+
};
|
|
251
|
+
const next = sql`(SELECT ${counters.lastNumber} FROM ${counters} WHERE ${counters.scope} = ${scope})`;
|
|
252
|
+
const [, saved] = await database.batch([
|
|
253
|
+
database.insert(counters).values({
|
|
254
|
+
scope,
|
|
255
|
+
lastNumber: 1
|
|
256
|
+
}).onConflictDoUpdate({
|
|
257
|
+
target: counters.scope,
|
|
258
|
+
set: { lastNumber: sql`${counters.lastNumber} + 1` }
|
|
259
|
+
}),
|
|
260
|
+
database.insert(threads).values({
|
|
261
|
+
...thread,
|
|
262
|
+
number: next
|
|
263
|
+
}).returning(),
|
|
264
|
+
database.insert(comments).values(comment)
|
|
265
|
+
]);
|
|
266
|
+
return toThread(saved[0], [comment]);
|
|
267
|
+
},
|
|
268
|
+
async reply(threadId, { body, author, mentions }, { allowResolved = false } = {}) {
|
|
269
|
+
const now = Date.now();
|
|
270
|
+
const comment = {
|
|
271
|
+
id: crypto.randomUUID(),
|
|
272
|
+
threadId,
|
|
273
|
+
body,
|
|
274
|
+
mentions: JSON.stringify(mentions),
|
|
275
|
+
author: JSON.stringify(author),
|
|
276
|
+
createdAt: now,
|
|
277
|
+
editedAt: null
|
|
278
|
+
};
|
|
279
|
+
const [inserted, , parents, rows] = await database.batch([
|
|
280
|
+
database.insert(comments).select(database.select({
|
|
281
|
+
id: sql`${comment.id}`.as("id"),
|
|
282
|
+
threadId: threads.id,
|
|
283
|
+
body: sql`${comment.body}`.as("body"),
|
|
284
|
+
mentions: sql`${comment.mentions}`.as("mentions"),
|
|
285
|
+
author: sql`${comment.author}`.as("author"),
|
|
286
|
+
createdAt: sql`${now}`.as("created_at"),
|
|
287
|
+
editedAt: sql`null`.as("edited_at")
|
|
288
|
+
}).from(threads).where(and(eq(threads.id, threadId), allowResolved ? void 0 : eq(threads.status, "open")))).returning(),
|
|
289
|
+
database.update(threads).set({ updatedAt: now }).where(and(eq(threads.id, threadId), exists(database.select({ id: comments.id }).from(comments).where(eq(comments.id, comment.id))))),
|
|
290
|
+
database.select().from(threads).where(eq(threads.id, threadId)),
|
|
291
|
+
database.select().from(comments).where(eq(comments.threadId, threadId)).orderBy(comments.createdAt)
|
|
292
|
+
]);
|
|
293
|
+
if (inserted[0] && parents[0]) return {
|
|
294
|
+
comment: toComment(inserted[0]),
|
|
295
|
+
thread: toThread(parents[0], rows)
|
|
296
|
+
};
|
|
297
|
+
return { error: parents[0]?.status === "resolved" ? "resolved" : "not-found" };
|
|
298
|
+
},
|
|
299
|
+
async edit(commentId, { body, mentions }) {
|
|
300
|
+
const now = Date.now();
|
|
301
|
+
const [updated] = await database.batch([database.update(comments).set({
|
|
302
|
+
body,
|
|
303
|
+
mentions: JSON.stringify(mentions),
|
|
304
|
+
editedAt: now
|
|
305
|
+
}).where(eq(comments.id, commentId)).returning(), database.update(threads).set({ updatedAt: now }).where(inArray(threads.id, database.select({ threadId: comments.threadId }).from(comments).where(eq(comments.id, commentId))))]);
|
|
306
|
+
return updated[0] ? toComment(updated[0]) : void 0;
|
|
307
|
+
},
|
|
308
|
+
async setStatus(threadId, status, by) {
|
|
309
|
+
const now = Date.now();
|
|
310
|
+
const [updated, rows] = await database.batch([database.update(threads).set(status === "resolved" ? {
|
|
311
|
+
status,
|
|
312
|
+
resolvedBy: JSON.stringify(by),
|
|
313
|
+
resolvedAt: now,
|
|
314
|
+
updatedAt: now
|
|
315
|
+
} : {
|
|
316
|
+
status,
|
|
317
|
+
resolvedBy: null,
|
|
318
|
+
resolvedAt: null,
|
|
319
|
+
updatedAt: now
|
|
320
|
+
}).where(eq(threads.id, threadId)).returning(), database.select().from(comments).where(eq(comments.threadId, threadId)).orderBy(comments.createdAt)]);
|
|
321
|
+
return updated[0] ? toThread(updated[0], rows) : void 0;
|
|
322
|
+
},
|
|
323
|
+
async removeThread(threadId) {
|
|
324
|
+
await database.batch([database.delete(comments).where(eq(comments.threadId, threadId)), database.delete(threads).where(eq(threads.id, threadId))]);
|
|
325
|
+
},
|
|
326
|
+
async removeComment(commentId) {
|
|
327
|
+
await database.delete(comments).where(eq(comments.id, commentId));
|
|
328
|
+
},
|
|
329
|
+
async removeScope(scope) {
|
|
330
|
+
const inScope = database.select({ id: threads.id }).from(threads).where(eq(threads.scope, scope));
|
|
331
|
+
const [, removed] = await database.batch([database.delete(comments).where(inArray(comments.threadId, inScope)), database.delete(threads).where(eq(threads.scope, scope)).returning({ id: threads.id })]);
|
|
332
|
+
return removed.map((row) => row.id);
|
|
333
|
+
},
|
|
334
|
+
async authors(scope, limit) {
|
|
335
|
+
const rows = await database.select({ author: comments.author }).from(comments).innerJoin(threads, eq(threads.id, comments.threadId)).where(eq(threads.scope, scope)).orderBy(desc(comments.createdAt)).limit(limit * 10);
|
|
336
|
+
const seen = /* @__PURE__ */ new Map();
|
|
337
|
+
for (const row of rows) {
|
|
338
|
+
const author = json(row.author);
|
|
339
|
+
if (author && !author.guest && !seen.has(author.id)) seen.set(author.id, author);
|
|
340
|
+
if (seen.size >= limit) break;
|
|
341
|
+
}
|
|
342
|
+
return [...seen.values()];
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
//#endregion
|
|
347
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
348
|
+
let activeEnv;
|
|
349
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
350
|
+
const runtimeGlobal = globalThis;
|
|
351
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
352
|
+
function runWithActiveCloudflareEnv(env, callback) {
|
|
353
|
+
return activeEnvStorage.run({ env }, callback);
|
|
354
|
+
}
|
|
355
|
+
function getActiveCloudflareEnv() {
|
|
356
|
+
const scoped = activeEnvStorage.getStore();
|
|
357
|
+
if (scoped) return scoped.env;
|
|
358
|
+
const host = globalThis;
|
|
359
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
360
|
+
}
|
|
361
|
+
function getActiveCloudflareBinding(name) {
|
|
362
|
+
const env = getActiveCloudflareEnv();
|
|
363
|
+
return env && Object.hasOwn(env, name) ? env[name] : void 0;
|
|
364
|
+
}
|
|
365
|
+
function ownValue(value, key) {
|
|
366
|
+
if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
|
|
367
|
+
return Reflect.get(value, key);
|
|
368
|
+
}
|
|
369
|
+
function ownObject(value) {
|
|
370
|
+
return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
|
|
371
|
+
}
|
|
372
|
+
/** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
|
|
373
|
+
function cloudflareOwners(target) {
|
|
374
|
+
const context = ownObject(ownValue(target, "context"));
|
|
375
|
+
const platform = ownObject(ownValue(context, "_platform"));
|
|
376
|
+
const req = ownObject(ownValue(target, "req"));
|
|
377
|
+
const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
|
|
378
|
+
return [
|
|
379
|
+
ownObject(ownValue(context, "cloudflare")),
|
|
380
|
+
ownObject(ownValue(platform, "cloudflare")),
|
|
381
|
+
ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
|
|
382
|
+
ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
|
|
383
|
+
];
|
|
384
|
+
}
|
|
385
|
+
function getCloudflareEnv(event, options = {}) {
|
|
386
|
+
const target = ownObject(event);
|
|
387
|
+
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
388
|
+
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
389
|
+
}
|
|
390
|
+
function resolveWaitUntil(event, options = {}) {
|
|
391
|
+
const target = ownObject(event);
|
|
392
|
+
const context = ownObject(ownValue(target, "context"));
|
|
393
|
+
const cloudflare = ownObject(ownValue(context, "cloudflare"));
|
|
394
|
+
const cloudflareContext = ownObject(ownValue(cloudflare, "context"));
|
|
395
|
+
const platformCloudflare = ownObject(ownValue(ownObject(ownValue(context, "_platform")), "cloudflare"));
|
|
396
|
+
const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
|
|
397
|
+
const req = ownObject(ownValue(target, "req"));
|
|
398
|
+
const reqCloudflare = ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"));
|
|
399
|
+
const reqCloudflareContext = ownObject(ownValue(reqCloudflare, "context"));
|
|
400
|
+
const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
|
|
401
|
+
const nodeCloudflare = ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"));
|
|
402
|
+
const hosts = [
|
|
403
|
+
context,
|
|
404
|
+
cloudflare,
|
|
405
|
+
cloudflareContext,
|
|
406
|
+
platformCloudflare,
|
|
407
|
+
platformCloudflareContext,
|
|
408
|
+
req,
|
|
409
|
+
reqCloudflare,
|
|
410
|
+
reqCloudflareContext,
|
|
411
|
+
nodeReq,
|
|
412
|
+
nodeCloudflare,
|
|
413
|
+
ownObject(ownValue(nodeCloudflare, "context"))
|
|
414
|
+
];
|
|
415
|
+
const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
|
|
416
|
+
for (const owner of owners) {
|
|
417
|
+
const waitUntil = ownValue(owner, "waitUntil");
|
|
418
|
+
if (typeof waitUntil === "function") return waitUntil.bind(owner);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/forge/github.ts
|
|
423
|
+
/** A GitHub request that failed, with the status and GitHub's message. */
|
|
424
|
+
var GitHubRequestError = class extends Error {
|
|
425
|
+
status;
|
|
426
|
+
name = "GitHubRequestError";
|
|
427
|
+
constructor(status, message) {
|
|
428
|
+
super(message);
|
|
429
|
+
this.status = status;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
const commentResponse = v.object({
|
|
433
|
+
id: v.number(),
|
|
434
|
+
node_id: v.string(),
|
|
435
|
+
html_url: v.string()
|
|
436
|
+
});
|
|
437
|
+
const commentListResponse = v.array(v.object({
|
|
438
|
+
...commentResponse.entries,
|
|
439
|
+
body: v.string()
|
|
440
|
+
}));
|
|
441
|
+
const pullsResponse = v.array(v.object({ number: v.number() }));
|
|
442
|
+
/** A Server Env value from the active Cloudflare bindings, else from `process.env`. */
|
|
443
|
+
function serverEnv(name) {
|
|
444
|
+
return getActiveCloudflareBinding(name) ?? globalThis.process?.env?.[name];
|
|
445
|
+
}
|
|
446
|
+
function createGitHubClient(options = {}) {
|
|
447
|
+
const apiUrl = (options.apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
448
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
449
|
+
const pullRequests = /* @__PURE__ */ new Map();
|
|
450
|
+
async function request(token, method, path, body) {
|
|
451
|
+
const response = await fetcher(`${apiUrl}${path}`, {
|
|
452
|
+
method,
|
|
453
|
+
headers: {
|
|
454
|
+
"accept": "application/vnd.github+json",
|
|
455
|
+
"authorization": `Bearer ${token}`,
|
|
456
|
+
"user-agent": "vitehub-comments",
|
|
457
|
+
"x-github-api-version": "2022-11-28",
|
|
458
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
459
|
+
},
|
|
460
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
461
|
+
});
|
|
462
|
+
if (!response.ok) {
|
|
463
|
+
const data = await response.json().catch(() => void 0);
|
|
464
|
+
const message = data && typeof data === "object" && "message" in data && typeof data.message === "string" ? data.message : response.statusText;
|
|
465
|
+
throw new GitHubRequestError(response.status, `GitHub ${method} ${path.split("?")[0]} failed with ${response.status}: ${message}`);
|
|
466
|
+
}
|
|
467
|
+
return response.status === 204 ? void 0 : await response.json();
|
|
468
|
+
}
|
|
469
|
+
async function graphql(token, query, variables) {
|
|
470
|
+
const graphqlUrl = apiUrl.endsWith("/api/v3") ? `${apiUrl.slice(0, -2)}graphql` : `${apiUrl}/graphql`;
|
|
471
|
+
const response = await fetcher(graphqlUrl, {
|
|
472
|
+
method: "POST",
|
|
473
|
+
headers: {
|
|
474
|
+
"authorization": `Bearer ${token}`,
|
|
475
|
+
"content-type": "application/json",
|
|
476
|
+
"user-agent": "vitehub-comments"
|
|
477
|
+
},
|
|
478
|
+
body: JSON.stringify({
|
|
479
|
+
query,
|
|
480
|
+
variables
|
|
481
|
+
})
|
|
482
|
+
});
|
|
483
|
+
const data = await response.json().catch(() => void 0);
|
|
484
|
+
const errors = data && typeof data === "object" && "errors" in data && Array.isArray(data.errors) ? data.errors : [];
|
|
485
|
+
if (!response.ok || errors.length) {
|
|
486
|
+
const message = errors[0] && typeof errors[0] === "object" && "message" in errors[0] ? String(errors[0].message) : response.statusText;
|
|
487
|
+
throw new GitHubRequestError(response.status, `GitHub GraphQL failed: ${message}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
async appToken(repository) {
|
|
492
|
+
const env = (name) => serverEnv(name);
|
|
493
|
+
const appId = readForgeEnv(forgeEnv.github.appId, env);
|
|
494
|
+
const privateKey = appId ? await readGitHubAppPrivateKey(readForgeEnv(forgeEnv.github.privateKey, env), readForgeEnv(forgeEnv.github.privateKeyPath, env)) : void 0;
|
|
495
|
+
if (appId && privateKey) {
|
|
496
|
+
const app = githubAppCredentials({
|
|
497
|
+
appId,
|
|
498
|
+
privateKey,
|
|
499
|
+
baseUrl: apiUrl,
|
|
500
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
501
|
+
userAgent: "vitehub-comments"
|
|
502
|
+
});
|
|
503
|
+
const installation = readForgeEnv(forgeEnv.github.installationId, env) ?? await app.installation(repository);
|
|
504
|
+
return (await app.installationToken(installation)).token;
|
|
505
|
+
}
|
|
506
|
+
const token = readForgeEnv(forgeEnv.github.token, env);
|
|
507
|
+
if (token) return token;
|
|
508
|
+
throw new GitHubRequestError(401, "Comments needs GitHub credentials to post to pull requests: VITEHUB_GITHUB_APP_ID with VITEHUB_GITHUB_PRIVATE_KEY, or VITEHUB_GITHUB_TOKEN.");
|
|
509
|
+
},
|
|
510
|
+
async findPullRequest(repository, branch) {
|
|
511
|
+
const key = `${repository}\0${branch}`;
|
|
512
|
+
const cached = pullRequests.get(key);
|
|
513
|
+
if (cached && cached.until > Date.now()) return cached.number;
|
|
514
|
+
const token = await this.appToken(repository);
|
|
515
|
+
const owner = repository.split("/")[0];
|
|
516
|
+
const number = v.parse(pullsResponse, await request(token, "GET", `/repos/${repository}/pulls?state=open&per_page=1&head=${encodeURIComponent(`${owner}:${branch}`)}`))[0]?.number;
|
|
517
|
+
pullRequests.set(key, {
|
|
518
|
+
number,
|
|
519
|
+
until: Date.now() + (number ? 5 : 1) * 6e4
|
|
520
|
+
});
|
|
521
|
+
return number;
|
|
522
|
+
},
|
|
523
|
+
async findComment(token, repository, pullRequest, marker) {
|
|
524
|
+
for (let page = 1;; page++) {
|
|
525
|
+
const comments = v.parse(commentListResponse, await request(token, "GET", `/repos/${repository}/issues/${pullRequest}/comments?per_page=100&page=${page}`));
|
|
526
|
+
const found = comments.find((comment) => comment.body.trimEnd().endsWith(marker));
|
|
527
|
+
if (found) return {
|
|
528
|
+
id: String(found.id),
|
|
529
|
+
nodeId: found.node_id,
|
|
530
|
+
url: found.html_url,
|
|
531
|
+
body: found.body
|
|
532
|
+
};
|
|
533
|
+
if (comments.length < 100) return;
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
async createComment(token, repository, pullRequest, body) {
|
|
537
|
+
const comment = v.parse(commentResponse, await request(token, "POST", `/repos/${repository}/issues/${pullRequest}/comments`, { body }));
|
|
538
|
+
return {
|
|
539
|
+
id: String(comment.id),
|
|
540
|
+
nodeId: comment.node_id,
|
|
541
|
+
url: comment.html_url
|
|
542
|
+
};
|
|
543
|
+
},
|
|
544
|
+
async updateComment(token, repository, id, body) {
|
|
545
|
+
await request(token, "PATCH", `/repos/${repository}/issues/comments/${id}`, { body });
|
|
546
|
+
},
|
|
547
|
+
async deleteComment(token, repository, id) {
|
|
548
|
+
try {
|
|
549
|
+
await request(token, "DELETE", `/repos/${repository}/issues/comments/${id}`);
|
|
550
|
+
} catch (error) {
|
|
551
|
+
if (!(error instanceof GitHubRequestError && error.status === 404)) throw error;
|
|
552
|
+
}
|
|
553
|
+
},
|
|
554
|
+
async minimize(token, nodeId, minimized) {
|
|
555
|
+
await graphql(token, minimized ? "mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: RESOLVED }) { clientMutationId } }" : "mutation($id: ID!) { unminimizeComment(input: { subjectId: $id }) { clientMutationId } }", { id: nodeId });
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/context.ts
|
|
561
|
+
/**
|
|
562
|
+
* The context of a thread as label and value pairs, in the order a person reads them: page, element, components,
|
|
563
|
+
* browser, build. The Console and Agent tools show these.
|
|
564
|
+
*/
|
|
565
|
+
function describeCommentContext(context) {
|
|
566
|
+
if (!context) return [];
|
|
567
|
+
const fields = [{
|
|
568
|
+
label: "URL",
|
|
569
|
+
value: context.url
|
|
570
|
+
}];
|
|
571
|
+
if (context.title) fields.push({
|
|
572
|
+
label: "Title",
|
|
573
|
+
value: context.title
|
|
574
|
+
});
|
|
575
|
+
if (context.route) fields.push({
|
|
576
|
+
label: "Route",
|
|
577
|
+
value: context.route
|
|
578
|
+
});
|
|
579
|
+
const element = context.element;
|
|
580
|
+
if (element) {
|
|
581
|
+
const tag = `<${element.tag}${element.id ? ` id="${element.id}"` : ""}${element.testId ? ` data-testid="${element.testId}"` : ""}>`;
|
|
582
|
+
fields.push({
|
|
583
|
+
label: "Element",
|
|
584
|
+
value: [
|
|
585
|
+
tag,
|
|
586
|
+
element.role && `role ${element.role}`,
|
|
587
|
+
element.name && `"${element.name}"`
|
|
588
|
+
].filter(Boolean).join(" ")
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
if (context.components?.length) {
|
|
592
|
+
fields.push({
|
|
593
|
+
label: "Components",
|
|
594
|
+
value: context.components.map((component) => component.name).join(" › ")
|
|
595
|
+
});
|
|
596
|
+
const files = [...new Set(context.components.flatMap((component) => component.files ?? []))];
|
|
597
|
+
if (files.length) fields.push({
|
|
598
|
+
label: "Files",
|
|
599
|
+
value: files.join(", ")
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
const environment = context.environment;
|
|
603
|
+
if (environment) {
|
|
604
|
+
fields.push({
|
|
605
|
+
label: "Viewport",
|
|
606
|
+
value: `${environment.viewport.width}×${environment.viewport.height} at ${environment.devicePixelRatio}x${environment.colorScheme ? `, ${environment.colorScheme}` : ""}`
|
|
607
|
+
});
|
|
608
|
+
fields.push({
|
|
609
|
+
label: "Browser",
|
|
610
|
+
value: environment.userAgent
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
if (context.build?.commit || context.build?.branch) fields.push({
|
|
614
|
+
label: "Build",
|
|
615
|
+
value: [context.build.branch, context.build.commit?.slice(0, 12)].filter(Boolean).join(" @ ")
|
|
616
|
+
});
|
|
617
|
+
return fields;
|
|
618
|
+
}
|
|
619
|
+
//#endregion
|
|
620
|
+
//#region src/forge/render.ts
|
|
621
|
+
/** The `<!-- -->` marker that ends every comment the sync posts, so people and tools can tell them apart. */
|
|
622
|
+
const forgeMarker = "vitehub-comments";
|
|
623
|
+
const summaryMarker = `<!-- ${forgeMarker} summary -->`;
|
|
624
|
+
function commentMarker(threadId, commentId) {
|
|
625
|
+
return `<!-- ${forgeMarker} thread=${threadId} comment=${commentId} -->`;
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Text that GitHub must not link: `@name` notifies a GitHub user, and `#3` links issue 3. Comment mentions and thread
|
|
629
|
+
* numbers belong to the app, so a word joiner breaks both without changing how they read.
|
|
630
|
+
*/
|
|
631
|
+
function unlinked(text) {
|
|
632
|
+
return text.replace(/@(?=[\w-])/g, "@").replace(/#(?=\d)/g, "#");
|
|
633
|
+
}
|
|
634
|
+
/** A thread number as people say it, "#3", that GitHub does not link to issue 3. */
|
|
635
|
+
function number(thread) {
|
|
636
|
+
return `#\u2060${thread.number}`;
|
|
637
|
+
}
|
|
638
|
+
function quote(text) {
|
|
639
|
+
return text.split("\n").map((line) => `> ${line}`).join("\n");
|
|
640
|
+
}
|
|
641
|
+
/** Comment text is plain text in the preview; keep it literal in GitHub Markdown too. */
|
|
642
|
+
function plainText(text) {
|
|
643
|
+
return unlinked(text).replace(/&/g, "&").replace(/[\\`*_{}[\]<>#+=!:|~-]/g, "\\$&").replace(/\b(www)\./gi, "$1\\.").replace(/^(\s*\d+)([.)])(?=\s)/gm, "$1\\$2").replace(/^[ \t]/gm, (char) => char === " " ? "	" : " ");
|
|
644
|
+
}
|
|
645
|
+
/** One line for a Markdown table cell. */
|
|
646
|
+
function cell(text) {
|
|
647
|
+
return plainText(text).replace(/\s+/g, " ").trim();
|
|
648
|
+
}
|
|
649
|
+
/** A code span for a Markdown table cell. GitHub shows `<` in a code span as typed, so only pipes are escaped. */
|
|
650
|
+
function code(text) {
|
|
651
|
+
return `\`${text.replace(/\s+/g, " ").replace(/\|/g, "\\|").replace(/`/g, "'").trim()}\``;
|
|
652
|
+
}
|
|
653
|
+
/** The first sentence of a comment, at most 100 characters. */
|
|
654
|
+
function headline(body) {
|
|
655
|
+
const first = body.trim().split(/(?<=[.!?])\s/, 1)[0] ?? "";
|
|
656
|
+
return first.length > 100 ? `${first.slice(0, 99).trimEnd()}…` : first;
|
|
657
|
+
}
|
|
658
|
+
function authorName(comment) {
|
|
659
|
+
return unlinked(`${comment.author.name}${comment.author.guest ? " (guest)" : ""}`);
|
|
660
|
+
}
|
|
661
|
+
/** The page of a thread in comment mode, with its thread open: the Console's **Open on page** link. */
|
|
662
|
+
function previewUrl(thread) {
|
|
663
|
+
if (!thread.context?.url) return;
|
|
664
|
+
try {
|
|
665
|
+
const url = new URL(thread.context.url);
|
|
666
|
+
url.hash = "";
|
|
667
|
+
return `${url.href}${url.search ? "&" : "?"}vitehub=comments#comment-${thread.id}`;
|
|
668
|
+
} catch {
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
function pageLink(thread) {
|
|
673
|
+
const url = previewUrl(thread);
|
|
674
|
+
return url ? `[\`${thread.page}\`](${url})` : `\`${thread.page}\``;
|
|
675
|
+
}
|
|
676
|
+
function where(thread) {
|
|
677
|
+
const element = thread.context?.element;
|
|
678
|
+
const name = element?.name ? ` “${cell(element.name).slice(0, 60)}”` : "";
|
|
679
|
+
return `**${number(thread)}** on ${pageLink(thread)}${element ? ` · \`${element.tag}\`${name}` : ""}`;
|
|
680
|
+
}
|
|
681
|
+
function details(thread) {
|
|
682
|
+
const fields = describeCommentContext(thread.context);
|
|
683
|
+
if (!fields.length) return "";
|
|
684
|
+
return [
|
|
685
|
+
"<details><summary>What they were looking at</summary>",
|
|
686
|
+
"",
|
|
687
|
+
"| | |",
|
|
688
|
+
"| --- | --- |",
|
|
689
|
+
...fields.map(({ label, value }) => {
|
|
690
|
+
return `| ${label} | ${label === "URL" ? cell(value) : label === "Files" ? value.split(", ").map(code).join("<br>") : code(value)} |`;
|
|
691
|
+
}),
|
|
692
|
+
"",
|
|
693
|
+
"</details>"
|
|
694
|
+
].join("\n");
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* The pull request comment of one comment. `author` posts with the person's own token, so the text is theirs; `app`
|
|
698
|
+
* posts for them, so it names them and quotes them.
|
|
699
|
+
*/
|
|
700
|
+
function renderComment(thread, comment, postedAs) {
|
|
701
|
+
const first = thread.comments[0]?.id === comment.id;
|
|
702
|
+
const body = plainText(comment.body);
|
|
703
|
+
const lines = [];
|
|
704
|
+
if (postedAs === "app") lines.push(first ? `**${plainText(authorName(comment))}** commented on the preview:` : `**${plainText(authorName(comment))}** replied on ${number(thread)}:`, "", quote(body));
|
|
705
|
+
else lines.push(body);
|
|
706
|
+
lines.push("");
|
|
707
|
+
if (first) {
|
|
708
|
+
lines.push(where(thread));
|
|
709
|
+
const context = details(thread);
|
|
710
|
+
if (context) lines.push("", context);
|
|
711
|
+
} else lines.push(`<sub>Reply on ${number(thread)} · ${pageLink(thread)}</sub>`);
|
|
712
|
+
lines.push("", commentMarker(thread.id, comment.id));
|
|
713
|
+
return lines.join("\n");
|
|
714
|
+
}
|
|
715
|
+
/** The summary comment of a pull request: every thread posted to it, by number, with its state. */
|
|
716
|
+
function renderSummary(input) {
|
|
717
|
+
const threads = [...input.threads].sort((a, b) => a.thread.number - b.thread.number);
|
|
718
|
+
const open = threads.filter(({ thread }) => thread.status === "open").length;
|
|
719
|
+
const site = threads.map(({ thread }) => thread.context?.url).find(Boolean);
|
|
720
|
+
let origin;
|
|
721
|
+
try {
|
|
722
|
+
origin = site ? new URL(site) : void 0;
|
|
723
|
+
} catch {}
|
|
724
|
+
const rows = threads.map(({ thread, url, failed }) => {
|
|
725
|
+
const first = thread.comments[0];
|
|
726
|
+
const text = cell(unlinked(headline(first?.body ?? "")));
|
|
727
|
+
const comment = url ? `[${text}](${url})` : text;
|
|
728
|
+
const shown = thread.status === "resolved" ? `~~${comment}~~` : comment;
|
|
729
|
+
const preview = previewUrl(thread);
|
|
730
|
+
const label = preview ? `[${number(thread)}](${preview})` : number(thread);
|
|
731
|
+
const state = thread.status === "resolved" ? "Resolved" : failed ? "Open, not posted yet" : "Open";
|
|
732
|
+
return `| ${label} | ${shown}<br><sub>${code(thread.page)} · ${cell(first ? authorName(first) : unlinked(thread.createdBy.name))}</sub> | ${state} |`;
|
|
733
|
+
});
|
|
734
|
+
return [
|
|
735
|
+
`### ${input.title}`,
|
|
736
|
+
"",
|
|
737
|
+
`**${open} open**, ${threads.length - open} resolved${origin ? ` on [${origin.host}](${origin.origin})` : ""}.`,
|
|
738
|
+
"",
|
|
739
|
+
"| # | Comment | State |",
|
|
740
|
+
"| --- | --- | --- |",
|
|
741
|
+
...rows,
|
|
742
|
+
"",
|
|
743
|
+
"<sub>ViteHub Comments keeps this comment up to date. Each thread is also its own comment below; reply on the page to keep the thread together.</sub>",
|
|
744
|
+
"",
|
|
745
|
+
summaryMarker
|
|
746
|
+
].join("\n");
|
|
747
|
+
}
|
|
748
|
+
//#endregion
|
|
749
|
+
//#region src/forge/tokens.ts
|
|
750
|
+
/** How long the GitHub token of a person's last request stays usable for the pull request sync that it started. */
|
|
751
|
+
const tokenLifetime = 6e5;
|
|
752
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
753
|
+
/**
|
|
754
|
+
* Keeps the GitHub token of a person who signed in with GitHub, so the pull request sync that runs after their request
|
|
755
|
+
* can post as them. The token lives in their session cookie; this copy stays in memory for ten minutes.
|
|
756
|
+
*/
|
|
757
|
+
function rememberGitHubToken(authorId, token) {
|
|
758
|
+
const now = Date.now();
|
|
759
|
+
if (tokens.size > 1e3) {
|
|
760
|
+
for (const [id, entry] of tokens) if (entry.until <= now) tokens.delete(id);
|
|
761
|
+
}
|
|
762
|
+
tokens.set(authorId, {
|
|
763
|
+
token,
|
|
764
|
+
until: now + tokenLifetime
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/** The GitHub token of a person's request in the last ten minutes. */
|
|
768
|
+
function recentGitHubToken(authorId) {
|
|
769
|
+
const entry = tokens.get(authorId);
|
|
770
|
+
if (!entry) return;
|
|
771
|
+
if (entry.until > Date.now()) return entry.token;
|
|
772
|
+
tokens.delete(authorId);
|
|
773
|
+
}
|
|
774
|
+
/** Drops the token of a person who signs out. */
|
|
775
|
+
function forgetGitHubToken(authorId) {
|
|
776
|
+
tokens.delete(authorId);
|
|
777
|
+
}
|
|
778
|
+
//#endregion
|
|
779
|
+
//#region src/forge/sync.ts
|
|
780
|
+
const { vitehubCommentForge: links } = commentsSchema;
|
|
781
|
+
/** How long a row that is being posted stays claimed, so a sync that died does not block the comment for good. */
|
|
782
|
+
const claimTimeout = 6e4;
|
|
783
|
+
/** Change detection only: two FNV-1a passes, as `commentRoom()` hashes pages. */
|
|
784
|
+
function digest(text) {
|
|
785
|
+
let a = 2166136261;
|
|
786
|
+
let b = 1523705862;
|
|
787
|
+
for (let index = 0; index < text.length; index++) {
|
|
788
|
+
const code = text.charCodeAt(index);
|
|
789
|
+
a = Math.imul(a ^ code, 16777619) >>> 0;
|
|
790
|
+
b = Math.imul(b ^ code, 2671213388) >>> 0;
|
|
791
|
+
}
|
|
792
|
+
return `${a.toString(16).padStart(8, "0")}${b.toString(16).padStart(8, "0")}`;
|
|
793
|
+
}
|
|
794
|
+
function message(error) {
|
|
795
|
+
return (error instanceof Error ? error.message : String(error)).slice(0, 500);
|
|
796
|
+
}
|
|
797
|
+
function linkOf(thread, byId) {
|
|
798
|
+
const rows = thread.comments.map((comment) => byId.get(comment.id));
|
|
799
|
+
const first = rows[0];
|
|
800
|
+
const target = first ?? rows.find((row) => row !== void 0);
|
|
801
|
+
if (!target) return null;
|
|
802
|
+
const error = rows.find((row) => row?.error)?.error;
|
|
803
|
+
return {
|
|
804
|
+
repository: target.repository,
|
|
805
|
+
pullRequest: target.pullRequest,
|
|
806
|
+
state: error ? "failed" : rows.some((row) => !row?.remoteId) ? "pending" : "posted",
|
|
807
|
+
...first?.url ? { url: first.url } : {},
|
|
808
|
+
...error ? { error } : {},
|
|
809
|
+
...first?.postedAs ? { postedAs: first.postedAs } : {}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
function authorizationFailed(error) {
|
|
813
|
+
return error instanceof GitHubRequestError && (error.status === 401 || error.status === 403 || error.status === 404);
|
|
814
|
+
}
|
|
815
|
+
/** Runs tasks with the same key one after another, so two syncs of a thread or a pull request never interleave. */
|
|
816
|
+
function serial() {
|
|
817
|
+
const tails = /* @__PURE__ */ new Map();
|
|
818
|
+
return (key, task) => {
|
|
819
|
+
const run = (tails.get(key) ?? Promise.resolve()).catch(() => {}).then(task);
|
|
820
|
+
tails.set(key, run);
|
|
821
|
+
run.catch(() => {}).finally(() => {
|
|
822
|
+
if (tails.get(key) === run) tails.delete(key);
|
|
823
|
+
});
|
|
824
|
+
return run;
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
function createForgeSync(options, input) {
|
|
828
|
+
const { database, store } = input;
|
|
829
|
+
const github = input.github ?? createGitHubClient({
|
|
830
|
+
...options.apiUrl ? { apiUrl: options.apiUrl } : {},
|
|
831
|
+
...options.fetch ? { fetch: options.fetch } : {}
|
|
832
|
+
});
|
|
833
|
+
const title = options.title ?? "Preview comments";
|
|
834
|
+
const inOrder = serial();
|
|
835
|
+
async function rowsOfThread(threadId) {
|
|
836
|
+
return await database.select().from(links).where(eq(links.threadId, threadId));
|
|
837
|
+
}
|
|
838
|
+
async function row(id) {
|
|
839
|
+
const [found] = await database.select().from(links).where(eq(links.id, id)).limit(1);
|
|
840
|
+
return found;
|
|
841
|
+
}
|
|
842
|
+
async function save(id, values) {
|
|
843
|
+
await database.update(links).set({
|
|
844
|
+
...values,
|
|
845
|
+
updatedAt: Date.now()
|
|
846
|
+
}).where(eq(links.id, id));
|
|
847
|
+
}
|
|
848
|
+
/** Pending writes are fenced by the claim's timestamp, including retries within the same millisecond. */
|
|
849
|
+
async function savePending(id, claimedAt, values) {
|
|
850
|
+
await database.update(links).set(values).where(and(eq(links.id, id), isNull(links.remoteId), eq(links.updatedAt, claimedAt)));
|
|
851
|
+
}
|
|
852
|
+
/** Claims a create. An expired owner may still finish; recordPosted reconciles its response. */
|
|
853
|
+
async function claim(id, existing, values) {
|
|
854
|
+
const now = Math.max(Date.now(), (existing?.updatedAt ?? 0) + 1);
|
|
855
|
+
if (!existing) return (await database.insert(links).values({
|
|
856
|
+
id,
|
|
857
|
+
...values,
|
|
858
|
+
minimized: false,
|
|
859
|
+
updatedAt: now
|
|
860
|
+
}).onConflictDoNothing().returning({ id: links.id })).length ? now : void 0;
|
|
861
|
+
if (existing.remoteId || !existing.error && existing.updatedAt > Date.now() - claimTimeout) return;
|
|
862
|
+
return (await database.update(links).set({
|
|
863
|
+
error: null,
|
|
864
|
+
updatedAt: now
|
|
865
|
+
}).where(and(eq(links.id, id), isNull(links.remoteId), eq(links.updatedAt, existing.updatedAt))).returning({ id: links.id })).length ? now : void 0;
|
|
866
|
+
}
|
|
867
|
+
/** Retain the remote identity before removing its link, so a failed DELETE can be retried without the thread. */
|
|
868
|
+
async function deletePosted(at, remoteId, token, existing) {
|
|
869
|
+
const id = `cleanup:${at.repository}#${remoteId}`;
|
|
870
|
+
await database.insert(links).values({
|
|
871
|
+
id,
|
|
872
|
+
threadId: null,
|
|
873
|
+
repository: at.repository,
|
|
874
|
+
pullRequest: at.pullRequest,
|
|
875
|
+
remoteId,
|
|
876
|
+
updatedAt: Date.now()
|
|
877
|
+
}).onConflictDoNothing();
|
|
878
|
+
if (existing && existing.id !== id) await database.delete(links).where(and(eq(links.id, existing.id), eq(links.remoteId, remoteId)));
|
|
879
|
+
await github.deleteComment(await token(), at.repository, remoteId);
|
|
880
|
+
await database.delete(links).where(eq(links.id, id));
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The first saved remote identity wins, even if its POST outlived its lease. A late creator cannot overwrite
|
|
884
|
+
* the winner, and queues deletion of its own extra comment before trying it. Cleanup survives a failed DELETE,
|
|
885
|
+
* even when the original thread and link have already been removed.
|
|
886
|
+
*/
|
|
887
|
+
async function recordPosted(id, at, posted, body, token, postedAs) {
|
|
888
|
+
const [saved] = await database.update(links).set({
|
|
889
|
+
remoteId: posted.id,
|
|
890
|
+
nodeId: posted.nodeId,
|
|
891
|
+
url: posted.url,
|
|
892
|
+
digest: digest(body),
|
|
893
|
+
error: null,
|
|
894
|
+
updatedAt: Date.now(),
|
|
895
|
+
...postedAs ? { postedAs } : {}
|
|
896
|
+
}).where(and(eq(links.id, id), isNull(links.remoteId))).returning();
|
|
897
|
+
if (saved) return saved;
|
|
898
|
+
const current = await row(id);
|
|
899
|
+
if (current?.remoteId !== posted.id) await deletePosted(at, posted.id, token);
|
|
900
|
+
return current;
|
|
901
|
+
}
|
|
902
|
+
/** Cleanup rows are independent of thread membership, so even a deleted thread can retry its remote deletions. */
|
|
903
|
+
async function retryCleanup() {
|
|
904
|
+
const pending = await database.select().from(links).where(like(links.id, "cleanup:%"));
|
|
905
|
+
for (const existing of pending) try {
|
|
906
|
+
await removeLink(existing, () => github.appToken(existing.repository));
|
|
907
|
+
} catch (error) {
|
|
908
|
+
await save(existing.id, { error: message(error) });
|
|
909
|
+
console.warn("[vitehub] Comments could not delete a pull request comment:", error);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
/** A claimed row may have reached GitHub before its creator died or lost the response. Never blindly repost it. */
|
|
913
|
+
async function recover(existing, token) {
|
|
914
|
+
const marker = existing.threadId === null ? summaryMarker : commentMarker(existing.threadId, existing.id);
|
|
915
|
+
const posted = await github.findComment(await token(), existing.repository, existing.pullRequest, marker);
|
|
916
|
+
if (!posted) return;
|
|
917
|
+
return await recordPosted(existing.id, existing, posted, posted.body, token);
|
|
918
|
+
}
|
|
919
|
+
async function removeLink(existing, token) {
|
|
920
|
+
let current = await row(existing.id);
|
|
921
|
+
if (!current) return;
|
|
922
|
+
if (!current.remoteId) {
|
|
923
|
+
const claimedAt = await claim(current.id, current, current);
|
|
924
|
+
if (claimedAt === void 0) return;
|
|
925
|
+
try {
|
|
926
|
+
await recover(current, token);
|
|
927
|
+
} catch (error) {
|
|
928
|
+
await savePending(current.id, claimedAt, { error: message(error) });
|
|
929
|
+
throw error;
|
|
930
|
+
}
|
|
931
|
+
if ((await database.delete(links).where(and(eq(links.id, current.id), isNull(links.remoteId))).returning({ id: links.id })).length) return;
|
|
932
|
+
current = await row(current.id);
|
|
933
|
+
}
|
|
934
|
+
if (current?.remoteId) await deletePosted(current, current.remoteId, token, current);
|
|
935
|
+
}
|
|
936
|
+
async function target(thread) {
|
|
937
|
+
const build = thread.context?.build;
|
|
938
|
+
const repository = options.repository ?? build?.repository;
|
|
939
|
+
if (!repository) return;
|
|
940
|
+
let pullRequest = options.pullRequest ? await options.pullRequest(thread) : build?.pullRequest;
|
|
941
|
+
if (!options.pullRequest && pullRequest === void 0 && build?.branch) pullRequest = await github.findPullRequest(repository, build.branch);
|
|
942
|
+
return pullRequest ? {
|
|
943
|
+
repository,
|
|
944
|
+
pullRequest
|
|
945
|
+
} : void 0;
|
|
946
|
+
}
|
|
947
|
+
/** The person's own GitHub token: `token(author)`, else the token of their GitHub sign-in to Comments. */
|
|
948
|
+
async function authorToken(comment) {
|
|
949
|
+
if (comment.author.guest) return;
|
|
950
|
+
if (!options.token) return recentGitHubToken(comment.author.id);
|
|
951
|
+
try {
|
|
952
|
+
return await options.token(comment.author) || void 0;
|
|
953
|
+
} catch (error) {
|
|
954
|
+
console.warn(`[vitehub] Comments forge token for ${comment.author.id} failed:`, error);
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
async function syncComment(thread, comment, existing, at, appToken) {
|
|
959
|
+
if (existing?.remoteId) {
|
|
960
|
+
const body = renderComment(thread, comment, existing.postedAs ?? "app");
|
|
961
|
+
const hash = digest(body);
|
|
962
|
+
try {
|
|
963
|
+
if (existing.digest !== hash) {
|
|
964
|
+
const own = existing.postedAs === "author" ? await authorToken(comment) : void 0;
|
|
965
|
+
try {
|
|
966
|
+
await github.updateComment(own ?? await appToken(), at.repository, existing.remoteId, body);
|
|
967
|
+
} catch (error) {
|
|
968
|
+
if (!own || !authorizationFailed(error)) throw error;
|
|
969
|
+
await github.updateComment(await appToken(), at.repository, existing.remoteId, body);
|
|
970
|
+
}
|
|
971
|
+
await save(comment.id, {
|
|
972
|
+
digest: hash,
|
|
973
|
+
error: null
|
|
974
|
+
});
|
|
975
|
+
} else if (existing.error) await save(comment.id, { error: null });
|
|
976
|
+
} catch (error) {
|
|
977
|
+
await save(comment.id, { error: message(error) });
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
const latest = await store.get(thread.id);
|
|
981
|
+
const edited = latest?.comments.find((item) => item.id === comment.id);
|
|
982
|
+
if (latest && edited && renderComment(latest, edited, existing.postedAs ?? "app") !== body) await syncComment(latest, edited, await row(comment.id), at, appToken);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
const claimedAt = await claim(comment.id, existing, {
|
|
986
|
+
threadId: thread.id,
|
|
987
|
+
...at
|
|
988
|
+
});
|
|
989
|
+
if (claimedAt === void 0) return;
|
|
990
|
+
try {
|
|
991
|
+
const recovered = existing ? await recover(existing, appToken) : void 0;
|
|
992
|
+
if (recovered?.remoteId) {
|
|
993
|
+
await syncComment(thread, comment, recovered, at, appToken);
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
const own = await authorToken(comment);
|
|
997
|
+
let postedAs = own ? "author" : "app";
|
|
998
|
+
let body = renderComment(thread, comment, postedAs);
|
|
999
|
+
let token = own ?? await appToken();
|
|
1000
|
+
let posted;
|
|
1001
|
+
try {
|
|
1002
|
+
await savePending(comment.id, claimedAt, { postedAs });
|
|
1003
|
+
posted = await github.createComment(token, at.repository, at.pullRequest, body);
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
if (!own || !authorizationFailed(error)) throw error;
|
|
1006
|
+
postedAs = "app";
|
|
1007
|
+
body = renderComment(thread, comment, postedAs);
|
|
1008
|
+
token = await appToken();
|
|
1009
|
+
await savePending(comment.id, claimedAt, { postedAs });
|
|
1010
|
+
posted = await github.createComment(token, at.repository, at.pullRequest, body);
|
|
1011
|
+
}
|
|
1012
|
+
const saved = await recordPosted(comment.id, at, posted, body, async () => token, postedAs);
|
|
1013
|
+
const latest = await store.get(thread.id);
|
|
1014
|
+
const edited = latest?.comments.find((item) => item.id === comment.id);
|
|
1015
|
+
if (saved?.remoteId && latest && edited) await syncComment(latest, edited, saved, at, appToken);
|
|
1016
|
+
} catch (error) {
|
|
1017
|
+
await savePending(comment.id, claimedAt, { error: message(error) });
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
async function summaryBody(at, extraId) {
|
|
1021
|
+
const rows = await database.select().from(links).where(and(eq(links.repository, at.repository), eq(links.pullRequest, at.pullRequest), isNotNull(links.threadId)));
|
|
1022
|
+
const ids = new Set(rows.map((item) => item.threadId));
|
|
1023
|
+
if (extraId) ids.add(extraId);
|
|
1024
|
+
const threads = (await Promise.all([...ids].map((threadId) => store.get(threadId)))).filter((thread) => thread !== void 0);
|
|
1025
|
+
if (!threads.length) return;
|
|
1026
|
+
const byId = new Map(rows.map((item) => [item.id, item]));
|
|
1027
|
+
return renderSummary({
|
|
1028
|
+
title,
|
|
1029
|
+
threads: threads.map((thread) => {
|
|
1030
|
+
const link = linkOf(thread, byId);
|
|
1031
|
+
return {
|
|
1032
|
+
thread,
|
|
1033
|
+
...link?.url ? { url: link.url } : {},
|
|
1034
|
+
failed: link?.state !== "posted"
|
|
1035
|
+
};
|
|
1036
|
+
})
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
async function syncSummary(at, extra) {
|
|
1040
|
+
await inOrder(`summary:${at.repository}#${at.pullRequest}`, async () => {
|
|
1041
|
+
const id = `summary:${at.repository}#${at.pullRequest}`;
|
|
1042
|
+
let appToken;
|
|
1043
|
+
const token = async () => appToken ??= await github.appToken(at.repository);
|
|
1044
|
+
while (true) {
|
|
1045
|
+
const existing = await row(id);
|
|
1046
|
+
const body = await summaryBody(at, extra?.id);
|
|
1047
|
+
if (body === void 0) {
|
|
1048
|
+
if (existing) await removeLink(existing, token);
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const hash = digest(body);
|
|
1052
|
+
if (existing?.remoteId) {
|
|
1053
|
+
if (existing.digest === hash) return;
|
|
1054
|
+
try {
|
|
1055
|
+
await github.updateComment(await token(), at.repository, existing.remoteId, body);
|
|
1056
|
+
await save(id, {
|
|
1057
|
+
digest: hash,
|
|
1058
|
+
error: null
|
|
1059
|
+
});
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
await save(id, { error: message(error) });
|
|
1062
|
+
throw error;
|
|
1063
|
+
}
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
const claimedAt = await claim(id, existing, {
|
|
1067
|
+
threadId: null,
|
|
1068
|
+
...at
|
|
1069
|
+
});
|
|
1070
|
+
if (claimedAt === void 0) return;
|
|
1071
|
+
try {
|
|
1072
|
+
if ((existing ? await recover(existing, token) : void 0)?.remoteId) continue;
|
|
1073
|
+
if (!await recordPosted(id, at, await github.createComment(await token(), at.repository, at.pullRequest, body), body, token, "app")) return;
|
|
1074
|
+
} catch (error) {
|
|
1075
|
+
await savePending(id, claimedAt, { error: message(error) });
|
|
1076
|
+
throw error;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
async function syncThread(threadId) {
|
|
1082
|
+
await retryCleanup();
|
|
1083
|
+
let thread = await store.get(threadId);
|
|
1084
|
+
const rows = await rowsOfThread(threadId);
|
|
1085
|
+
const at = rows[0] ? {
|
|
1086
|
+
repository: rows[0].repository,
|
|
1087
|
+
pullRequest: rows[0].pullRequest
|
|
1088
|
+
} : thread ? await target(thread) : void 0;
|
|
1089
|
+
if (!at) return;
|
|
1090
|
+
let appToken;
|
|
1091
|
+
const token = async () => appToken ??= await github.appToken(at.repository);
|
|
1092
|
+
let delay = 10;
|
|
1093
|
+
try {
|
|
1094
|
+
while (thread && !(await row(`summary:${at.repository}#${at.pullRequest}`))?.remoteId) {
|
|
1095
|
+
await syncSummary(at, thread);
|
|
1096
|
+
if ((await row(`summary:${at.repository}#${at.pullRequest}`))?.remoteId) break;
|
|
1097
|
+
thread = await store.get(threadId);
|
|
1098
|
+
if (!thread) break;
|
|
1099
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1100
|
+
delay = Math.min(delay * 2, 1e3);
|
|
1101
|
+
}
|
|
1102
|
+
} catch (error) {
|
|
1103
|
+
const first = (await store.get(threadId))?.comments[0];
|
|
1104
|
+
if (first) await database.insert(links).values({
|
|
1105
|
+
id: first.id,
|
|
1106
|
+
threadId,
|
|
1107
|
+
...at,
|
|
1108
|
+
error: message(error),
|
|
1109
|
+
updatedAt: Date.now()
|
|
1110
|
+
}).onConflictDoNothing();
|
|
1111
|
+
console.warn("[vitehub] Comments could not post the pull request summary:", error);
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
thread = await store.get(threadId);
|
|
1115
|
+
const live = new Set(thread?.comments.map((comment) => comment.id) ?? []);
|
|
1116
|
+
for (const gone of rows.filter((item) => !live.has(item.id))) await removeLink(gone, token);
|
|
1117
|
+
if (thread) {
|
|
1118
|
+
for (const comment of thread.comments) {
|
|
1119
|
+
if (await store.threadOf(comment.id) !== threadId) continue;
|
|
1120
|
+
await syncComment(thread, comment, rows.find((item) => item.id === comment.id), at, token);
|
|
1121
|
+
}
|
|
1122
|
+
while (true) {
|
|
1123
|
+
const latest = await store.get(threadId);
|
|
1124
|
+
if (!latest) break;
|
|
1125
|
+
const first = await row(latest.comments[0]?.id ?? "");
|
|
1126
|
+
const resolved = latest.status === "resolved";
|
|
1127
|
+
if (!first?.nodeId || first.minimized === resolved) break;
|
|
1128
|
+
try {
|
|
1129
|
+
await github.minimize(await token(), first.nodeId, resolved);
|
|
1130
|
+
await save(first.id, { minimized: resolved });
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
await save(first.id, { error: message(error) });
|
|
1133
|
+
console.warn(`[vitehub] Comments could not ${resolved ? "hide" : "show"} the comment of thread ${thread.id}:`, error);
|
|
1134
|
+
break;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
const latest = await store.get(threadId);
|
|
1139
|
+
const remaining = new Set(latest?.comments.map((comment) => comment.id) ?? []);
|
|
1140
|
+
for (const gone of (await rowsOfThread(threadId)).filter((item) => !remaining.has(item.id))) await removeLink(gone, token);
|
|
1141
|
+
await syncSummary(at);
|
|
1142
|
+
}
|
|
1143
|
+
return {
|
|
1144
|
+
async sync(threadId) {
|
|
1145
|
+
await inOrder(`thread:${threadId}`, () => syncThread(threadId));
|
|
1146
|
+
},
|
|
1147
|
+
async attach(threads) {
|
|
1148
|
+
if (!threads.length) return threads;
|
|
1149
|
+
const rows = await database.select().from(links).where(inArray(links.threadId, threads.map((thread) => thread.id)));
|
|
1150
|
+
const byId = new Map(rows.map((item) => [item.id, item]));
|
|
1151
|
+
return threads.map((thread) => {
|
|
1152
|
+
return {
|
|
1153
|
+
...thread,
|
|
1154
|
+
forge: linkOf(thread, byId)
|
|
1155
|
+
};
|
|
1156
|
+
});
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
//#endregion
|
|
1161
|
+
//#region src/index.ts
|
|
1162
|
+
/**
|
|
1163
|
+
* The policy without `authorize`, for every action: a person signed in with GitHub needs push access to the repository
|
|
1164
|
+
* of the build; any other signed-in user may; anonymous people may only on the development server, as guests.
|
|
1165
|
+
* `development` comes from Vite's command in the generated Nitro plugin, and defaults to false.
|
|
1166
|
+
*/
|
|
1167
|
+
function defaultPolicy(user, development = false) {
|
|
1168
|
+
if (!user) return development;
|
|
1169
|
+
return user.github ? user.github.write : true;
|
|
1170
|
+
}
|
|
1171
|
+
const runtimes = /* @__PURE__ */ new WeakMap();
|
|
1172
|
+
function defineComments(configuration = {}) {
|
|
1173
|
+
const input = configuration;
|
|
1174
|
+
const options = {
|
|
1175
|
+
...input,
|
|
1176
|
+
authorize: input.authorize ? (context) => input.authorize(context) : void 0
|
|
1177
|
+
};
|
|
1178
|
+
const store = () => runtimes.get(comments)?.store;
|
|
1179
|
+
const pending = /* @__PURE__ */ new Set();
|
|
1180
|
+
/** Starts the pull request sync of a thread after a change. Errors are logged; the next change tries again. */
|
|
1181
|
+
function changed(threadId) {
|
|
1182
|
+
const forge = runtimes.get(comments)?.forge;
|
|
1183
|
+
if (!forge) return;
|
|
1184
|
+
const task = forge.sync(threadId).catch((error) => console.error(`[vitehub] Comments could not sync thread ${threadId} to its pull request:`, error)).finally(() => pending.delete(task));
|
|
1185
|
+
pending.add(task);
|
|
1186
|
+
}
|
|
1187
|
+
async function withForge(threads) {
|
|
1188
|
+
const forge = runtimes.get(comments)?.forge;
|
|
1189
|
+
return forge ? await forge.attach(threads) : threads;
|
|
1190
|
+
}
|
|
1191
|
+
const notInstalled = () => [commentsErrors.COMMENTS_NOT_INSTALLED(), void 0];
|
|
1192
|
+
const notFound = (id) => [commentsErrors.COMMENTS_NOT_FOUND({ id }), void 0];
|
|
1193
|
+
async function notify(thread, comment) {
|
|
1194
|
+
if (!options.onComment) return;
|
|
1195
|
+
try {
|
|
1196
|
+
await options.onComment({
|
|
1197
|
+
thread,
|
|
1198
|
+
comment,
|
|
1199
|
+
mentions: comment.mentions
|
|
1200
|
+
});
|
|
1201
|
+
} catch (error) {
|
|
1202
|
+
console.error("[vitehub] Comments onComment failed:", error);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
const comments = {
|
|
1206
|
+
options,
|
|
1207
|
+
async list(query = {}) {
|
|
1208
|
+
const current = store();
|
|
1209
|
+
if (!current) return notInstalled();
|
|
1210
|
+
const limit = Math.min(Math.max(query.limit ?? 200, 1), 500);
|
|
1211
|
+
return [void 0, await withForge(await current.list({
|
|
1212
|
+
scope: query.scope,
|
|
1213
|
+
page: query.page === void 0 ? void 0 : normalizeCommentPage(query.page),
|
|
1214
|
+
status: query.status,
|
|
1215
|
+
limit
|
|
1216
|
+
}))];
|
|
1217
|
+
},
|
|
1218
|
+
async get(id) {
|
|
1219
|
+
const current = store();
|
|
1220
|
+
if (!current) return notInstalled();
|
|
1221
|
+
const [thread] = await withForge([await current.get(id)].filter((found) => found !== void 0));
|
|
1222
|
+
return thread ? [void 0, thread] : notFound(id);
|
|
1223
|
+
},
|
|
1224
|
+
async getByComment(commentId) {
|
|
1225
|
+
const current = store();
|
|
1226
|
+
if (!current) return notInstalled();
|
|
1227
|
+
const threadId = await current.threadOf(commentId);
|
|
1228
|
+
const [thread] = await withForge([threadId ? await current.get(threadId) : void 0].filter((found) => found !== void 0));
|
|
1229
|
+
return thread ? [void 0, thread] : notFound(commentId);
|
|
1230
|
+
},
|
|
1231
|
+
async getByNumber(scope, number) {
|
|
1232
|
+
const current = store();
|
|
1233
|
+
if (!current) return notInstalled();
|
|
1234
|
+
const [thread] = await withForge([await current.getByNumber(scope, number)].filter((found) => found !== void 0));
|
|
1235
|
+
return thread ? [void 0, thread] : notFound(`${scope}#${number}`);
|
|
1236
|
+
},
|
|
1237
|
+
async create(input) {
|
|
1238
|
+
const current = store();
|
|
1239
|
+
if (!current) return notInstalled();
|
|
1240
|
+
const parsed = v.safeParse(createThreadSchema, input);
|
|
1241
|
+
if (!parsed.success) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(parsed.issues) }), void 0];
|
|
1242
|
+
if (parsed.output.scope === "pages" && !parsed.output.anchor) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: "anchor: A thread on a page needs an anchor." }), void 0];
|
|
1243
|
+
const thread = await current.create({
|
|
1244
|
+
...parsed.output,
|
|
1245
|
+
page: normalizeCommentPage(parsed.output.page)
|
|
1246
|
+
});
|
|
1247
|
+
await notify(thread, thread.comments[0]);
|
|
1248
|
+
changed(thread.id);
|
|
1249
|
+
return [void 0, thread];
|
|
1250
|
+
},
|
|
1251
|
+
async reply(threadId, input, replyOptions = {}) {
|
|
1252
|
+
const current = store();
|
|
1253
|
+
if (!current) return notInstalled();
|
|
1254
|
+
const parsed = v.safeParse(replySchema, input);
|
|
1255
|
+
if (!parsed.success) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(parsed.issues) }), void 0];
|
|
1256
|
+
const result = await current.reply(threadId, parsed.output, replyOptions);
|
|
1257
|
+
if ("error" in result) return result.error === "resolved" ? [commentsErrors.COMMENTS_RESOLVED(), void 0] : notFound(threadId);
|
|
1258
|
+
const { comment, thread } = result;
|
|
1259
|
+
await notify(thread, comment);
|
|
1260
|
+
changed(threadId);
|
|
1261
|
+
return [void 0, comment];
|
|
1262
|
+
},
|
|
1263
|
+
async resolve(threadId, { by }) {
|
|
1264
|
+
const current = store();
|
|
1265
|
+
if (!current) return notInstalled();
|
|
1266
|
+
const thread = await current.setStatus(threadId, "resolved", by);
|
|
1267
|
+
if (thread) changed(threadId);
|
|
1268
|
+
return thread ? [void 0, thread] : notFound(threadId);
|
|
1269
|
+
},
|
|
1270
|
+
async reopen(threadId) {
|
|
1271
|
+
const current = store();
|
|
1272
|
+
if (!current) return notInstalled();
|
|
1273
|
+
const thread = await current.setStatus(threadId, "open", null);
|
|
1274
|
+
if (thread) changed(threadId);
|
|
1275
|
+
return thread ? [void 0, thread] : notFound(threadId);
|
|
1276
|
+
},
|
|
1277
|
+
async remove(threadId) {
|
|
1278
|
+
const current = store();
|
|
1279
|
+
if (!current) return notInstalled();
|
|
1280
|
+
if (!await current.get(threadId)) return notFound(threadId);
|
|
1281
|
+
await current.removeThread(threadId);
|
|
1282
|
+
changed(threadId);
|
|
1283
|
+
return [void 0, void 0];
|
|
1284
|
+
},
|
|
1285
|
+
async removeComment(commentId) {
|
|
1286
|
+
const current = store();
|
|
1287
|
+
if (!current) return notInstalled();
|
|
1288
|
+
const threadId = await current.threadOf(commentId);
|
|
1289
|
+
if (!threadId) return notFound(commentId);
|
|
1290
|
+
if ((await current.get(threadId))?.comments[0]?.id === commentId) await current.removeThread(threadId);
|
|
1291
|
+
else await current.removeComment(commentId);
|
|
1292
|
+
changed(threadId);
|
|
1293
|
+
return [void 0, void 0];
|
|
1294
|
+
},
|
|
1295
|
+
async edit(commentId, input) {
|
|
1296
|
+
const current = store();
|
|
1297
|
+
if (!current) return notInstalled();
|
|
1298
|
+
const parsed = v.safeParse(editSchema, input);
|
|
1299
|
+
if (!parsed.success) return [commentsErrors.COMMENTS_INVALID_INPUT({ issue: describeIssue(parsed.issues) }), void 0];
|
|
1300
|
+
const comment = await current.edit(commentId, parsed.output);
|
|
1301
|
+
if (comment) changed(comment.threadId);
|
|
1302
|
+
return comment ? [void 0, comment] : notFound(commentId);
|
|
1303
|
+
},
|
|
1304
|
+
async removeScope(scope) {
|
|
1305
|
+
const current = store();
|
|
1306
|
+
if (!current) return notInstalled();
|
|
1307
|
+
if (!v.is(scopeSchema, scope)) return [void 0, { removed: 0 }];
|
|
1308
|
+
const removed = await current.removeScope(scope);
|
|
1309
|
+
for (const threadId of removed) changed(threadId);
|
|
1310
|
+
return [void 0, { removed: removed.length }];
|
|
1311
|
+
},
|
|
1312
|
+
async can(context) {
|
|
1313
|
+
if (!options.authorize) return defaultPolicy(context.user, runtimes.get(comments)?.development);
|
|
1314
|
+
const scope = context.scope ?? context.thread?.scope ?? "pages";
|
|
1315
|
+
return await options.authorize({
|
|
1316
|
+
...context,
|
|
1317
|
+
scope
|
|
1318
|
+
}) !== false;
|
|
1319
|
+
},
|
|
1320
|
+
async people({ query, user, scope = commentsPageScope }) {
|
|
1321
|
+
const current = store();
|
|
1322
|
+
if (!current) return notInstalled();
|
|
1323
|
+
const all = options.people ? await options.people({
|
|
1324
|
+
query,
|
|
1325
|
+
user
|
|
1326
|
+
}) : await current.authors(scope, 50);
|
|
1327
|
+
const needle = query.trim().toLowerCase();
|
|
1328
|
+
return [void 0, all.filter((person) => !needle || person.name.toLowerCase().includes(needle)).slice(0, 20).map(({ id, name }) => ({
|
|
1329
|
+
id,
|
|
1330
|
+
name
|
|
1331
|
+
}))];
|
|
1332
|
+
},
|
|
1333
|
+
async sync(threadId) {
|
|
1334
|
+
await runtimes.get(comments)?.forge?.sync(threadId);
|
|
1335
|
+
},
|
|
1336
|
+
async flush() {
|
|
1337
|
+
while (pending.size) await Promise.all(pending);
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
return Object.freeze(Object.assign(comments, defineComments$1({
|
|
1341
|
+
...input,
|
|
1342
|
+
authorize: input.authorize ? async (context) => await input.authorize(context) === true : void 0
|
|
1343
|
+
})));
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Connects a Comments definition to its Database. The generated Nitro plugin calls it when the server starts; call it
|
|
1347
|
+
* yourself only in tests or outside ViteHub. Only the Vite dev server enables `development`; it defaults to false.
|
|
1348
|
+
*/
|
|
1349
|
+
function installComments(comments, runtime) {
|
|
1350
|
+
const store = createCommentsStore(runtime.database);
|
|
1351
|
+
const forge = comments.options.forge ? createForgeSync(comments.options.forge, {
|
|
1352
|
+
database: runtime.database,
|
|
1353
|
+
store
|
|
1354
|
+
}) : void 0;
|
|
1355
|
+
runtimes.set(comments, {
|
|
1356
|
+
store,
|
|
1357
|
+
forge,
|
|
1358
|
+
development: runtime.development === true
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
//#endregion
|
|
1362
|
+
export { commentsErrors as _, rememberGitHubToken as a, getCloudflareEnv as c, anchorSchema as d, bodySchema as f, pageSchema as g, mentionsSchema as h, forgetGitHubToken as i, resolveWaitUntil as l, describeIssue as m, defineComments as n, describeCommentContext as o, contextSchema as p, installComments as r, getActiveCloudflareBinding as s, defaultPolicy as t, runWithActiveCloudflareEnv as u };
|