@vite-hub/comments 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -0
  3. package/dist/anchor.d.ts +40 -0
  4. package/dist/anchor.js +128 -0
  5. package/dist/client.d.ts +101 -0
  6. package/dist/client.js +553 -0
  7. package/dist/console-BIz9t2cO.d.ts +243 -0
  8. package/dist/database/postgres.d.ts +1011 -0
  9. package/dist/database/postgres.js +60 -0
  10. package/dist/database-BSnVrwHn.js +60 -0
  11. package/dist/database-C-ktS9Do.js +95 -0
  12. package/dist/database-Cb2xjC1V.d.ts +1096 -0
  13. package/dist/database.d.ts +104 -0
  14. package/dist/database.js +3 -0
  15. package/dist/define-BzW2Ychn.d.ts +46 -0
  16. package/dist/define-Cbhl6QVJ.js +32 -0
  17. package/dist/errors-BAQYcy3_.d.ts +89 -0
  18. package/dist/errors-DeD6wTCl.js +77 -0
  19. package/dist/h3-v1-request-DDGXJ9E7.js +166 -0
  20. package/dist/identity-3qtVC4rF.js +34 -0
  21. package/dist/index-DklG2Etf.d.ts +111 -0
  22. package/dist/index.d.ts +7 -0
  23. package/dist/index.js +5 -0
  24. package/dist/operations-0B0QTVWX.d.ts +138 -0
  25. package/dist/operations-NZG5dB8y.js +732 -0
  26. package/dist/operations.d.ts +7 -0
  27. package/dist/operations.js +2 -0
  28. package/dist/overlay/overlay.js +195 -0
  29. package/dist/page/loader.js +22 -0
  30. package/dist/page-BtXADR6d.d.ts +21 -0
  31. package/dist/page-BuroSMXO.js +38 -0
  32. package/dist/page-tools-shared-D-amu6sx.js +53 -0
  33. package/dist/plugin-QElKQYkA.js +725 -0
  34. package/dist/realtime.d.ts +18 -0
  35. package/dist/realtime.js +48 -0
  36. package/dist/request-DVc3M_AG.js +14 -0
  37. package/dist/rpc.d.ts +29 -0
  38. package/dist/rpc.js +75 -0
  39. package/dist/runtime/auth.d.ts +6 -0
  40. package/dist/runtime/auth.js +15 -0
  41. package/dist/runtime/connect/node.d.ts +1 -0
  42. package/dist/runtime/connect/node.js +2 -0
  43. package/dist/runtime/connect.d.ts +1 -0
  44. package/dist/runtime/connect.js +2 -0
  45. package/dist/runtime/console.d.ts +5 -0
  46. package/dist/runtime/console.js +59 -0
  47. package/dist/runtime/index.d.ts +222 -0
  48. package/dist/runtime/index.js +665 -0
  49. package/dist/server-BomGg3Gb.js +63 -0
  50. package/dist/server.d.ts +94 -0
  51. package/dist/server.js +326 -0
  52. package/dist/src-CRTwnaEG.js +1362 -0
  53. package/dist/testing.d.ts +30 -0
  54. package/dist/testing.js +175 -0
  55. package/dist/types-Cj8K7Vx7.d.ts +176 -0
  56. package/dist/types-Un2dcJWD.d.ts +288 -0
  57. package/dist/vite.d.ts +304 -0
  58. package/dist/vite.js +1921 -0
  59. package/package.json +156 -4
@@ -0,0 +1,732 @@
1
+ import { t as commentsErrorDiagnostics } from "./errors-DeD6wTCl.js";
2
+ import { t as builtinCommentSubjects } from "./define-Cbhl6QVJ.js";
3
+ import { t as commentsRuntime } from "./server-BomGg3Gb.js";
4
+ import { defineDiagnostics } from "nostics";
5
+ import { toJsonSchema } from "@valibot/to-json-schema";
6
+ import * as v from "valibot";
7
+ //#region \0rolldown/runtime.js
8
+ var __defProp = Object.defineProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ //#endregion
19
+ //#region ../internal/src/error-diagnostics.ts
20
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
21
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
22
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
23
+ codes: {
24
+ INTERNAL_R0012: dynamicError,
25
+ INTERNAL_R0013: dynamicError,
26
+ INTERNAL_R0014: {
27
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
28
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
29
+ },
30
+ INTERNAL_R0020: {
31
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
32
+ why: ({ message }) => message === void 0 ? "" : String(message)
33
+ },
34
+ INTERNAL_R0021: {
35
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
36
+ why: ({ message }) => message === void 0 ? "" : String(message)
37
+ },
38
+ INTERNAL_R0022: {
39
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
40
+ why: ({ message }) => message === void 0 ? "" : String(message)
41
+ },
42
+ INTERNAL_R0024: {
43
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
44
+ why: ({ message }) => message === void 0 ? "" : String(message)
45
+ },
46
+ INTERNAL_R0023: {
47
+ fix: "Ask for access to the section of this operation.",
48
+ why: ({ message }) => message === void 0 ? "" : String(message)
49
+ },
50
+ INTERNAL_B0001: dynamicError,
51
+ INTERNAL_B0002: dynamicError,
52
+ INTERNAL_B0003: dynamicError,
53
+ INTERNAL_B0004: dynamicError,
54
+ INTERNAL_B0005: dynamicError,
55
+ INTERNAL_B0006: dynamicError,
56
+ INTERNAL_B0007: dynamicError,
57
+ INTERNAL_B0008: dynamicError,
58
+ INTERNAL_B0009: dynamicError,
59
+ INTERNAL_B0010: dynamicError,
60
+ INTERNAL_B0011: dynamicError,
61
+ INTERNAL_B0012: dynamicError,
62
+ INTERNAL_B0013: dynamicError,
63
+ INTERNAL_B0014: dynamicError,
64
+ INTERNAL_B0015: dynamicError,
65
+ INTERNAL_B0016: dynamicError,
66
+ INTERNAL_B0017: dynamicError,
67
+ INTERNAL_B0018: dynamicError,
68
+ INTERNAL_B0019: dynamicError,
69
+ INTERNAL_B0020: dynamicError,
70
+ INTERNAL_B0021: dynamicError,
71
+ INTERNAL_B0022: dynamicError,
72
+ INTERNAL_B0023: dynamicError,
73
+ INTERNAL_B0024: dynamicError,
74
+ INTERNAL_B0025: dynamicError,
75
+ INTERNAL_B0026: dynamicError,
76
+ INTERNAL_B0027: dynamicError,
77
+ INTERNAL_B0028: dynamicError,
78
+ INTERNAL_B0029: dynamicError,
79
+ INTERNAL_B0030: dynamicError,
80
+ INTERNAL_B0031: dynamicError,
81
+ INTERNAL_B0032: dynamicError,
82
+ INTERNAL_B0033: dynamicError,
83
+ INTERNAL_B0034: dynamicError,
84
+ INTERNAL_B0035: dynamicError,
85
+ INTERNAL_B0036: dynamicError,
86
+ INTERNAL_B0037: dynamicError,
87
+ INTERNAL_B0038: dynamicError,
88
+ INTERNAL_B0039: dynamicError,
89
+ INTERNAL_B0040: dynamicError,
90
+ INTERNAL_B0041: dynamicError,
91
+ INTERNAL_B0042: dynamicError,
92
+ INTERNAL_B0043: dynamicError,
93
+ INTERNAL_B0044: dynamicError,
94
+ INTERNAL_B0045: dynamicError,
95
+ INTERNAL_B0046: dynamicError,
96
+ INTERNAL_B0047: dynamicError,
97
+ INTERNAL_B0048: {
98
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
99
+ why: ({ message }) => message === void 0 ? "" : String(message)
100
+ },
101
+ INTERNAL_B0049: {
102
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
103
+ why: ({ message }) => message === void 0 ? "" : String(message)
104
+ },
105
+ INTERNAL_B0050: {
106
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
107
+ why: ({ message }) => message === void 0 ? "" : String(message)
108
+ },
109
+ INTERNAL_R0025: {
110
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
111
+ why: ({ message }) => message === void 0 ? "" : String(message)
112
+ },
113
+ INTERNAL_R0026: {
114
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
115
+ fix: "Review the operation, then run it again with --yes to confirm the change."
116
+ },
117
+ INTERNAL_C0001: dynamicError,
118
+ INTERNAL_C0002: dynamicError,
119
+ INTERNAL_R0001: dynamicError,
120
+ INTERNAL_R0002: dynamicError,
121
+ INTERNAL_R0003: dynamicError,
122
+ INTERNAL_R0004: dynamicError,
123
+ INTERNAL_R0005: dynamicError,
124
+ INTERNAL_R0006: dynamicError,
125
+ INTERNAL_R0007: dynamicError,
126
+ INTERNAL_R0008: dynamicError,
127
+ INTERNAL_R0009: dynamicError,
128
+ INTERNAL_R0010: dynamicError,
129
+ INTERNAL_R0011: dynamicError
130
+ }
131
+ });
132
+ //#endregion
133
+ //#region ../internal/src/standard-schema.ts
134
+ function readOwn(value, key) {
135
+ if (value === null || Object(value) !== value) return;
136
+ try {
137
+ return Reflect.get(Object(value), key);
138
+ } catch {
139
+ return;
140
+ }
141
+ }
142
+ function isRecord(value) {
143
+ return value !== null && Object(value) === value && !Array.isArray(value);
144
+ }
145
+ /**
146
+ * Read a Standard JSON Schema projection without throwing.
147
+ *
148
+ * Returns `undefined` when the schema has no `~standard.jsonSchema`, when the library cannot represent the type
149
+ * (Zod throws for `Date`), or when the projection is not an object. Callers decide how to fall back.
150
+ */
151
+ function standardJsonSchema(schema, direction, target = "draft-2020-12", libraryOptions) {
152
+ const jsonSchema = readOwn(readOwn(schema, "~standard"), "jsonSchema");
153
+ const project = readOwn(jsonSchema, direction);
154
+ if (typeof project !== "function") return;
155
+ try {
156
+ const result = project.call(jsonSchema, libraryOptions ? {
157
+ target,
158
+ libraryOptions
159
+ } : { target });
160
+ return isRecord(result) ? result : void 0;
161
+ } catch {
162
+ return;
163
+ }
164
+ }
165
+ //#endregion
166
+ //#region ../internal/src/valibot.ts
167
+ const valibotTargets = /* @__PURE__ */ new Set([
168
+ "draft-07",
169
+ "draft-2020-12",
170
+ "openapi-3.0"
171
+ ]);
172
+ function isValibotTarget(value) {
173
+ return valibotTargets.has(String(value));
174
+ }
175
+ /**
176
+ * Add Standard JSON Schema conversion to a plain Valibot schema. Valibot schemas validate as Standard Schema but carry
177
+ * no JSON Schema, so forms, tools, and model providers would get no shape for them. Other schemas, Valibot schemas that
178
+ * already convert, and async Valibot schemas return unchanged. The copy keeps every Valibot property, so validation
179
+ * does not change.
180
+ *
181
+ * `target` fixes the JSON Schema dialect. Without it, each conversion uses the dialect that the caller asks for.
182
+ */
183
+ function withValibotJsonSchema(schema, options = {}) {
184
+ const standard = schema["~standard"];
185
+ if (standard.vendor !== "valibot" || Reflect.get(schema, "async") === true) return schema;
186
+ if (Object.hasOwn(standard, "jsonSchema") && standard.jsonSchema) return schema;
187
+ const convert = (typeMode) => (request) => {
188
+ const target = options.target ?? request.target;
189
+ if (!isValibotTarget(target)) throw new Error(`[vitehub] Valibot cannot convert a schema to the ${String(target)} JSON Schema target.`);
190
+ return toJsonSchema(schema, {
191
+ target,
192
+ typeMode,
193
+ errorMode: "ignore"
194
+ });
195
+ };
196
+ return {
197
+ ...schema,
198
+ "~standard": {
199
+ ...standard,
200
+ jsonSchema: {
201
+ input: convert("input"),
202
+ output: convert("output")
203
+ }
204
+ }
205
+ };
206
+ }
207
+ //#endregion
208
+ //#region ../internal/src/operations.ts
209
+ const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
210
+ const kinds = /* @__PURE__ */ new Set([
211
+ "read",
212
+ "write",
213
+ "destructive"
214
+ ]);
215
+ function isObject(value) {
216
+ return value !== null && Object(value) === value && !Array.isArray(value);
217
+ }
218
+ function invalidDefinition(name, reason) {
219
+ return internalErrorDiagnostics.INTERNAL_R0020({ message: `[vitehub] Operation ${JSON.stringify(name)} is invalid: ${reason}` });
220
+ }
221
+ function checkDefinition(definition) {
222
+ if (!isObject(definition)) throw invalidDefinition(void 0, "defineOperation() takes an object.");
223
+ const { name } = definition;
224
+ if (String(name) !== name || !nameFormat.test(name)) throw invalidDefinition(name, "the name must look like `section.verb`, in lower case.");
225
+ if (String(definition.description) !== definition.description || !definition.description) throw invalidDefinition(name, "add a one sentence description.");
226
+ const { section } = definition;
227
+ if (section !== false && !(section instanceof Function) && (String(section) !== section || !section)) throw invalidDefinition(name, "section must be a Console section id, a function, or false.");
228
+ if (!kinds.has(String(definition.kind))) throw invalidDefinition(name, "kind must be \"read\", \"write\", or \"destructive\".");
229
+ const input = definition.input;
230
+ if (!isObject(input) || !isObject(input["~standard"]) || !(input["~standard"].validate instanceof Function)) throw invalidDefinition(name, "input must be a Standard Schema, such as a valibot object.");
231
+ if (!(definition.run instanceof Function)) throw invalidDefinition(name, "run must be a function.");
232
+ const { maxRequestBytes } = definition;
233
+ if (maxRequestBytes !== void 0 && (!Number.isInteger(maxRequestBytes) || Number(maxRequestBytes) < 65536)) throw invalidDefinition(name, `maxRequestBytes can only raise the limit above ${defaultRequestBytes} bytes (64 KiB).`);
234
+ if (definition.readOnlyWhen !== void 0 && !(definition.readOnlyWhen instanceof Function)) throw invalidDefinition(name, "readOnlyWhen must be a function.");
235
+ }
236
+ /** The default limit of a call, in bytes. */
237
+ const defaultRequestBytes = 65536;
238
+ /** Input keys that the generated CLI commands read themselves. */
239
+ const reservedOperationFlags = [
240
+ "input",
241
+ "json",
242
+ "timeout",
243
+ "url",
244
+ "yes"
245
+ ];
246
+ /**
247
+ * Define one operation. The Console, the CLI, MCP, and agent tools call the same definition. Contribute it with
248
+ * `vitehub: { operations: [{ module, export }] }` on a Vite plugin.
249
+ */
250
+ function defineOperation(definition) {
251
+ checkDefinition(definition);
252
+ const defined = {
253
+ ...definition,
254
+ input: withValibotJsonSchema(definition.input)
255
+ };
256
+ const properties = operationInputJsonSchema(defined).properties;
257
+ const clashes = isObject(properties) ? Object.keys(properties).filter((key) => reservedOperationFlags.includes(key)) : [];
258
+ if (clashes.length) throw invalidDefinition(definition.name, `the input key ${clashes.map((key) => JSON.stringify(key)).join(", ")} is a CLI flag of every command (${reservedOperationFlags.join(", ")}). Rename it.`);
259
+ return defined;
260
+ }
261
+ /** JSON Schema of the input, for CLI flags and MCP tool schemas. Falls back to an open object. */
262
+ function operationInputJsonSchema(operation) {
263
+ return standardJsonSchema(operation.input, "input") ?? { type: "object" };
264
+ }
265
+ /**
266
+ * Whether the checked access covers the section. Without `call`, a read-only grant (`"kv:read"`) counts, so the answer
267
+ * is whether the section is visible. With `call`, a read-only grant allows only a `read` operation or a call that only
268
+ * reads. Every surface (RPC, CLI, agents, MCP) checks access here.
269
+ */
270
+ function operationAccessAllows(access, section, call) {
271
+ if (section === void 0) return false;
272
+ if (section === false || access.sections === "all") return true;
273
+ if (access.sections.includes(section)) return true;
274
+ if (!access.sections.includes(`${section}:read`)) return false;
275
+ return call === void 0 || call.kind === "read" || call.readOnly === true;
276
+ }
277
+ /**
278
+ * An app path: one slash, then no second slash or backslash (`//host` and `/\host` leave the site), no whitespace,
279
+ * and no `?` or `#`, which a link adds itself.
280
+ */
281
+ const pagePath = /^\/(?![/\\])[^\s\\?#]*$/;
282
+ function isPagePath(value) {
283
+ return value.length <= 500 && pagePath.test(value) && !new URL(value, "https://comments.invalid").pathname.startsWith("//");
284
+ }
285
+ //#endregion
286
+ //#region src/operations-core/operations.ts
287
+ var operations_exports = /* @__PURE__ */ __exportAll({
288
+ commentsOperations: () => commentsOperations,
289
+ maximumCommentBodyLength: () => maximumCommentBodyLength
290
+ });
291
+ /** Longest message, in characters. */
292
+ const maximumCommentBodyLength = 1e4;
293
+ const maximumMentions = 20;
294
+ const maximumAttachments = 10;
295
+ const defaultLimit = 200;
296
+ const maximumLimit = 500;
297
+ const maximumSuggestions = 10;
298
+ const minimumQuery = 2;
299
+ /** Threads that `authorize` checks at once. */
300
+ const authorizeConcurrency = 16;
301
+ const thousandths = v.pipe(v.number(), v.minValue(0), v.maxValue(1e3));
302
+ const selector = v.pipe(v.string(), v.minLength(1), v.maxLength(500));
303
+ const quote = v.pipe(v.string(), v.maxLength(2e3));
304
+ const anchor = v.union([
305
+ v.strictObject({ kind: v.literal("page") }),
306
+ v.strictObject({
307
+ kind: v.literal("element"),
308
+ selector,
309
+ x: thousandths,
310
+ y: thousandths
311
+ }),
312
+ v.strictObject({
313
+ exact: v.pipe(v.string(), v.minLength(1), v.maxLength(2e3)),
314
+ kind: v.literal("text"),
315
+ prefix: quote,
316
+ selector,
317
+ suffix: quote
318
+ }),
319
+ v.pipe(v.strictObject({
320
+ height: v.pipe(v.number(), v.minValue(1), v.maxValue(1e3)),
321
+ kind: v.literal("area"),
322
+ selector,
323
+ width: v.pipe(v.number(), v.minValue(1), v.maxValue(1e3)),
324
+ x: thousandths,
325
+ y: thousandths
326
+ }), v.check((area) => area.x + area.width <= 1e3 && area.y + area.height <= 1e3, "An area must stay inside the element box: x + width and y + height are at most 1000.")),
327
+ v.pipe(v.strictObject({
328
+ height: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(1e3))),
329
+ kind: v.literal("image"),
330
+ selector,
331
+ width: v.optional(v.pipe(v.number(), v.minValue(1), v.maxValue(1e3))),
332
+ x: thousandths,
333
+ y: thousandths
334
+ }), v.check((area) => area.width === void 0 === (area.height === void 0), "An image area needs width and height together."), v.check((area) => area.x + (area.width ?? 0) <= 1e3 && area.y + (area.height ?? 0) <= 1e3, "An image area must stay inside the element box."))
335
+ ]);
336
+ const subject = v.strictObject({
337
+ id: v.pipe(v.string(), v.minLength(1), v.maxLength(500)),
338
+ kind: v.pipe(v.string(), v.minLength(1), v.maxLength(40))
339
+ });
340
+ const page = v.pipe(v.string(), v.check(isPagePath, "A page is an app path that starts with one \"/\", such as \"/pricing\", without \"?\" or \"#\"."));
341
+ const cursor = v.strictObject({
342
+ id: v.pipe(v.string(), v.minLength(1), v.maxLength(100)),
343
+ updatedAt: v.number()
344
+ });
345
+ const text = v.pipe(v.string(), v.maxLength(maximumCommentBodyLength));
346
+ const id = v.pipe(v.string(), v.minLength(1), v.maxLength(100));
347
+ const mentions = v.optional(v.pipe(v.array(id), v.maxLength(maximumMentions)));
348
+ const attachments = v.optional(v.pipe(v.array(v.pipe(v.string(), v.minLength(1), v.maxLength(500))), v.maxLength(maximumAttachments)));
349
+ const threadId = v.strictObject({ threadId: id });
350
+ function fail(error, status) {
351
+ return Object.assign(error, { status });
352
+ }
353
+ /** Public identity for stored comments and notifications; policies keep the full user. */
354
+ function personOf(user) {
355
+ return {
356
+ id: user.id,
357
+ ...user.name ? { name: user.name } : {},
358
+ ...user.image ? { image: user.image } : {}
359
+ };
360
+ }
361
+ function actorOf(actor) {
362
+ return actor ? {
363
+ id: actor.id,
364
+ ...actor.label ? { name: actor.label } : {}
365
+ } : void 0;
366
+ }
367
+ async function caller(context) {
368
+ const actor = actorOf(context.actor);
369
+ return {
370
+ runtime: await commentsRuntime(),
371
+ user: context.user,
372
+ ...actor ? { actor } : {}
373
+ };
374
+ }
375
+ /** Without an `authorize` policy nobody can do anything. */
376
+ function policy(who) {
377
+ const { authorize } = who.runtime.definition;
378
+ if (!authorize) throw fail(commentsErrorDiagnostics.COMMENTS_R0006(), 403);
379
+ return authorize;
380
+ }
381
+ /** Asks the policy, with the thread and its subject, or the subject a thread would start on. */
382
+ async function permitted(who, action, target = {}, user = who.user) {
383
+ const subject = target.subject ?? target.thread?.subject;
384
+ const actor = user === who.user ? who.actor : void 0;
385
+ return Boolean(await policy(who)({
386
+ action,
387
+ user: user ? { ...user } : null,
388
+ ...actor ? { actor } : {},
389
+ ...target.thread ? { thread: target.thread } : {},
390
+ ...subject ? { subject } : {}
391
+ }));
392
+ }
393
+ async function allow(who, action, target) {
394
+ if (!await permitted(who, action, target)) throw fail(commentsErrorDiagnostics.COMMENTS_R0009({ action }), 403);
395
+ }
396
+ function author(who) {
397
+ if (!who.user) throw fail(commentsErrorDiagnostics.COMMENTS_R0012(), 401);
398
+ return personOf(who.user);
399
+ }
400
+ function scopeOf(runtime, target) {
401
+ const definition = [...builtinCommentSubjects, ...runtime.definition.subjects ?? []].reverse().find((candidate) => candidate.kind === target.kind);
402
+ if (!definition) throw fail(commentsErrorDiagnostics.COMMENTS_R0008({ kind: target.kind }), 400);
403
+ if (target.kind === "page" && !isPagePath(target.id)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: "A page subject takes an app path that starts with one \"/\", such as \"/pricing\", without \"?\" or \"#\"." }), 400);
404
+ if (target.kind === "content" && !target.id.includes("/")) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: "A content subject is \"<collection>/<id>\"." }), 400);
405
+ return definition.scope(target.id);
406
+ }
407
+ function escapeRegExp(value) {
408
+ return value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
409
+ }
410
+ /** The mentioned ids must be real people, and the text must name each of them with `@name`. */
411
+ async function checkMentions(who, body, ids) {
412
+ const unique = [...new Set(ids ?? [])];
413
+ if (!unique.length) return [];
414
+ const found = new Map((await (who.runtime.users ? who.runtime.users.byIds(unique) : who.runtime.store.knownUsersByIds(unique, (thread) => permitted(who, "read", { thread }).catch(() => false)))).map((person) => [person.id, person]));
415
+ const people = [];
416
+ for (const mentioned of unique) {
417
+ const person = found.get(mentioned);
418
+ if (!person) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `The mentioned user ${JSON.stringify(mentioned)} does not exist.` }), 400);
419
+ const name = person.name ?? person.id;
420
+ if (!new RegExp(`(^|[^\\p{L}\\p{N}\\p{M}_])@${escapeRegExp(name)}(?=$|[^\\p{L}\\p{N}\\p{M}_])`, "iu").test(body)) throw fail(commentsErrorDiagnostics.COMMENTS_R0007({ message: `The text does not name @${name}, but the comment mentions ${name}.` }), 400);
421
+ people.push(person);
422
+ }
423
+ return people;
424
+ }
425
+ function cleanBody(body) {
426
+ const trimmed = body.trim();
427
+ if (!trimmed) throw fail(commentsErrorDiagnostics.COMMENTS_R0005(), 400);
428
+ return trimmed;
429
+ }
430
+ function newId(prefix) {
431
+ return `${prefix}_${crypto.randomUUID()}`;
432
+ }
433
+ /**
434
+ * Runs `onMention` after the change is saved, for the mentioned people that may read the thread. The mention stays in
435
+ * the text for the others. A failure never fails the comment.
436
+ */
437
+ function announce(who, context, thread, message, mentioned) {
438
+ const onMention = who.runtime.definition.onMention;
439
+ if (!onMention || !message || !mentioned.length) return;
440
+ const task = (async () => {
441
+ try {
442
+ const readers = [];
443
+ for (const person of mentioned) if (await permitted(who, "read", { thread }, person).catch(() => false)) readers.push(personOf(person));
444
+ if (readers.length) await onMention({
445
+ mentioned: readers,
446
+ message,
447
+ thread
448
+ });
449
+ } catch (error) {
450
+ globalThis.console.error("[vitehub] comments onMention failed.", error);
451
+ }
452
+ })();
453
+ if (context.waitUntil) context.waitUntil(task);
454
+ }
455
+ /** A thread that does not exist and one that the caller may not read look the same: not found. */
456
+ async function load(who, threadIdValue) {
457
+ policy(who);
458
+ const found = await who.runtime.store.getById(threadIdValue);
459
+ if (!found || !await permitted(who, "read", { thread: found })) throw fail(commentsErrorDiagnostics.COMMENTS_R0002({ id: threadIdValue }), 404);
460
+ return found;
461
+ }
462
+ async function mapLimit(items, limit, run) {
463
+ const results = Array.from({ length: items.length });
464
+ let next = 0;
465
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
466
+ while (next < items.length) {
467
+ const index = next++;
468
+ results[index] = await run(items[index]);
469
+ }
470
+ }));
471
+ return results;
472
+ }
473
+ function cursorOf(thread) {
474
+ return {
475
+ id: thread.id,
476
+ updatedAt: thread.updatedAt
477
+ };
478
+ }
479
+ function noAttachments(attachmentList) {
480
+ if (attachmentList?.length) throw fail(commentsErrorDiagnostics.COMMENTS_R0014(), 400);
481
+ }
482
+ const list = defineOperation({
483
+ description: "List comment threads, newest first, filtered by subject, page, status, author, or mention. Pass the last thread as `before` for the next page.",
484
+ input: v.strictObject({
485
+ before: v.optional(cursor),
486
+ limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(maximumLimit))),
487
+ mentions: v.optional(v.boolean()),
488
+ mine: v.optional(v.boolean()),
489
+ page: v.optional(page),
490
+ status: v.optional(v.picklist(["open", "resolved"])),
491
+ subject: v.optional(subject)
492
+ }),
493
+ kind: "read",
494
+ name: "comments.list",
495
+ run: async (input, context) => {
496
+ const who = await caller(context);
497
+ policy(who);
498
+ const limit = input.limit ?? defaultLimit;
499
+ const readable = [];
500
+ let before = input.before;
501
+ while (readable.length < limit) {
502
+ const threads = await who.runtime.store.list({
503
+ ...input,
504
+ limit,
505
+ ...before ? { before } : {},
506
+ ...who.user ? { userId: who.user.id } : {}
507
+ });
508
+ const allowed = await mapLimit(threads, authorizeConcurrency, (thread) => permitted(who, "read", { thread }).catch(() => false));
509
+ for (const [index, thread] of threads.entries()) if (allowed[index] && readable.length < limit) readable.push(thread);
510
+ if (threads.length < limit) break;
511
+ before = cursorOf(threads.at(-1));
512
+ }
513
+ return readable;
514
+ },
515
+ section: "comments"
516
+ });
517
+ const get = defineOperation({
518
+ description: "Read one comment thread by id, or by number inside its scope. A thread that does not exist or that you may not read is null.",
519
+ input: v.union([v.strictObject({ id }), v.strictObject({
520
+ n: v.pipe(v.number(), v.integer(), v.minValue(1)),
521
+ scope: v.pipe(v.string(), v.minLength(1), v.maxLength(200))
522
+ })]),
523
+ kind: "read",
524
+ name: "comments.get",
525
+ run: async (input, context) => {
526
+ const who = await caller(context);
527
+ policy(who);
528
+ const found = "id" in input ? await who.runtime.store.getById(input.id) : await who.runtime.store.getByNumber(input.scope, input.n);
529
+ return found && await permitted(who, "read", { thread: found }) ? found : null;
530
+ },
531
+ section: "comments"
532
+ });
533
+ const create = defineOperation({
534
+ description: "Start a comment thread on a subject, such as a page, with an anchor and a first message.",
535
+ input: v.strictObject({
536
+ anchor,
537
+ attachments,
538
+ body: text,
539
+ mentions,
540
+ subject
541
+ }),
542
+ kind: "write",
543
+ name: "comments.create",
544
+ run: async (input, context) => {
545
+ const who = await caller(context);
546
+ await allow(who, "read", { subject: input.subject });
547
+ await allow(who, "write", { subject: input.subject });
548
+ noAttachments(input.attachments);
549
+ const person = author(who);
550
+ const body = cleanBody(input.body);
551
+ const mentioned = await checkMentions(who, body, input.mentions);
552
+ const now = Date.now();
553
+ const created = await who.runtime.store.createThread({
554
+ anchor: input.anchor,
555
+ attachments: [],
556
+ author: person,
557
+ body,
558
+ id: newId("message"),
559
+ mentions: mentioned.map((entry) => entry.id),
560
+ now,
561
+ scope: scopeOf(who.runtime, input.subject),
562
+ subject: input.subject,
563
+ threadId: newId("thread"),
564
+ ...who.actor ? { actor: who.actor } : {}
565
+ });
566
+ announce(who, context, created, created.messages[0], mentioned);
567
+ return created;
568
+ },
569
+ section: "comments"
570
+ });
571
+ const reply = defineOperation({
572
+ description: "Add a message to a comment thread.",
573
+ input: v.strictObject({
574
+ attachments,
575
+ body: text,
576
+ mentions,
577
+ threadId: id
578
+ }),
579
+ kind: "write",
580
+ name: "comments.reply",
581
+ run: async (input, context) => {
582
+ const who = await caller(context);
583
+ const found = await load(who, input.threadId);
584
+ await allow(who, "write", { thread: found });
585
+ noAttachments(input.attachments);
586
+ const person = author(who);
587
+ const body = cleanBody(input.body);
588
+ const mentioned = await checkMentions(who, body, input.mentions);
589
+ const messageId = newId("message");
590
+ const next = await who.runtime.store.addMessage(found.id, {
591
+ attachments: [],
592
+ author: person,
593
+ body,
594
+ id: messageId,
595
+ mentions: mentioned.map((entry) => entry.id),
596
+ now: Date.now(),
597
+ ...who.actor ? { actor: who.actor } : {}
598
+ });
599
+ announce(who, context, next, next.messages.find((entry) => entry.id === messageId), mentioned);
600
+ return next;
601
+ },
602
+ section: "comments"
603
+ });
604
+ const edit = defineOperation({
605
+ description: "Change the text of your own message.",
606
+ input: v.strictObject({
607
+ body: text,
608
+ mentions,
609
+ messageId: id,
610
+ threadId: id
611
+ }),
612
+ kind: "write",
613
+ name: "comments.edit",
614
+ run: async (input, context) => {
615
+ const who = await caller(context);
616
+ const found = await load(who, input.threadId);
617
+ if (who.actor) await allow(who, "write", { thread: found });
618
+ const target = found.messages.find((entry) => entry.id === input.messageId);
619
+ if (!target) throw fail(commentsErrorDiagnostics.COMMENTS_R0003({ messageId: input.messageId }), 404);
620
+ if (!who.user || target.author.id !== who.user.id) throw fail(commentsErrorDiagnostics.COMMENTS_R0004(), 403);
621
+ const body = cleanBody(input.body);
622
+ const mentioned = await checkMentions(who, body, input.mentions);
623
+ const next = await who.runtime.store.editMessage(found.id, target.id, {
624
+ body,
625
+ mentions: mentioned.map((entry) => entry.id),
626
+ now: Date.now()
627
+ });
628
+ announce(who, context, next, next.messages.find((entry) => entry.id === target.id), mentioned.filter((entry) => !target.mentions.includes(entry.id)));
629
+ return next;
630
+ },
631
+ section: "comments"
632
+ });
633
+ const remove = defineOperation({
634
+ description: "Delete a message, or the whole thread. Deleting the first message deletes the thread.",
635
+ input: v.strictObject({
636
+ messageId: v.optional(id),
637
+ threadId: id
638
+ }),
639
+ kind: "destructive",
640
+ name: "comments.delete",
641
+ run: async (input, context) => {
642
+ const who = await caller(context);
643
+ const found = await load(who, input.threadId);
644
+ const target = input.messageId === void 0 ? void 0 : found.messages.find((entry) => entry.id === input.messageId);
645
+ if (input.messageId !== void 0 && !target) throw fail(commentsErrorDiagnostics.COMMENTS_R0003({ messageId: input.messageId }), 404);
646
+ const deletesThread = !target || target.id === found.messages[0]?.id;
647
+ const ownerId = who.user && !who.actor ? who.user.id : void 0;
648
+ const owns = ownerId !== void 0 && (deletesThread ? found.messages.every((entry) => entry.author.id === ownerId) : target.author.id === ownerId);
649
+ if (!owns) await allow(who, "delete", { thread: found });
650
+ if (deletesThread) {
651
+ if (await who.runtime.store.deleteThread(found.id, owns ? ownerId : void 0) === false) throw fail(commentsErrorDiagnostics.COMMENTS_R0009({ action: "delete" }), 403);
652
+ return null;
653
+ }
654
+ return who.runtime.store.deleteMessage(found.id, target.id, Date.now());
655
+ },
656
+ section: "comments"
657
+ });
658
+ function statusOperation(name, status, description) {
659
+ return defineOperation({
660
+ description,
661
+ input: threadId,
662
+ kind: "write",
663
+ name,
664
+ run: async (input, context) => {
665
+ const who = await caller(context);
666
+ const found = await load(who, input.threadId);
667
+ await allow(who, "resolve", { thread: found });
668
+ return who.runtime.store.setStatus(found.id, status, author(who), Date.now());
669
+ },
670
+ section: "comments"
671
+ });
672
+ }
673
+ const users = defineOperation({
674
+ description: "Find people to mention by name. Needs at least two characters, and the right to write.",
675
+ input: v.strictObject({
676
+ limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(maximumSuggestions))),
677
+ query: v.pipe(v.string(), v.maxLength(100))
678
+ }),
679
+ kind: "read",
680
+ name: "comments.users",
681
+ run: async (input, context) => {
682
+ const who = await caller(context);
683
+ await allow(who, "read");
684
+ await allow(who, "write");
685
+ const query = input.query.trim();
686
+ if (query.length < minimumQuery) return [];
687
+ const limit = Math.min(input.limit ?? 5, maximumSuggestions);
688
+ return (who.runtime.users ? await who.runtime.users.search(query, limit) : await who.runtime.store.knownUsers(query, limit, (thread) => permitted(who, "read", { thread }).catch(() => false))).slice(0, limit).map((person) => ({
689
+ id: person.id,
690
+ ...person.name ? { name: person.name } : {},
691
+ ...person.image ? { image: person.image } : {}
692
+ }));
693
+ },
694
+ section: "comments"
695
+ });
696
+ const session = defineOperation({
697
+ description: "Tell the comments overlay who is signed in and what that person may do. Nothing else leaves the server.",
698
+ input: v.strictObject({ subject: v.optional(subject) }),
699
+ kind: "read",
700
+ name: "comments.session",
701
+ run: async (input, context) => {
702
+ const who = await caller(context);
703
+ if (!who.user) return {
704
+ canRead: false,
705
+ canWrite: false,
706
+ user: null
707
+ };
708
+ const can = (action) => who.runtime.definition.authorize ? permitted(who, action, { subject: input.subject }).catch(() => false) : Promise.resolve(false);
709
+ const [canRead, canWrite] = await Promise.all([can("read"), can("write")]);
710
+ return {
711
+ canRead,
712
+ canWrite: canRead && canWrite && operationAccessAllows(context.access, "comments", { kind: "write" }),
713
+ user: personOf(who.user)
714
+ };
715
+ },
716
+ section: "comments"
717
+ });
718
+ /** The comment operations. The Console, the CLI, MCP, and the comments client call them. */
719
+ const commentsOperations = [
720
+ list,
721
+ get,
722
+ create,
723
+ reply,
724
+ edit,
725
+ remove,
726
+ statusOperation("comments.resolve", "resolved", "Mark a comment thread as resolved."),
727
+ statusOperation("comments.reopen", "open", "Open a resolved comment thread again."),
728
+ users,
729
+ session
730
+ ];
731
+ //#endregion
732
+ export { maximumCommentBodyLength as n, operations_exports as r, commentsOperations as t };