@vite-hub/comments 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +79 -31
  2. package/dist/anchor.d.ts +7 -4
  3. package/dist/anchor.js +10 -5
  4. package/dist/client-diagnostics-CcFpkbAk.js +40 -0
  5. package/dist/client.d.ts +78 -3
  6. package/dist/client.js +198 -13
  7. package/dist/{console-BIz9t2cO.d.ts → console-h4KlhIik.d.ts} +97 -8
  8. package/dist/context-BqIsmYP1.js +61 -0
  9. package/dist/database/postgres.d.ts +738 -347
  10. package/dist/database/postgres.js +28 -7
  11. package/dist/{database-Cb2xjC1V.d.ts → database-CA1aHKN7.d.ts} +675 -276
  12. package/dist/database.d.ts +6 -98
  13. package/dist/database.js +2 -3
  14. package/dist/define-43mMR39K.js +89 -0
  15. package/dist/define-B3TF9zzn.d.ts +204 -0
  16. package/dist/errors-4gelGVmK.js +57 -0
  17. package/dist/errors-C6qptPoG.js +135 -0
  18. package/dist/errors-CyQyKAvy.d.ts +185 -0
  19. package/dist/fold-name-B7Zb3-MF.js +7 -0
  20. package/dist/{identity-3qtVC4rF.js → identity-CBOzgxSf.js} +7 -2
  21. package/dist/index-DNhy69Wt.d.ts +83 -0
  22. package/dist/index.d.ts +7 -7
  23. package/dist/index.js +196 -5
  24. package/dist/install-BcMPgPk_.js +1154 -0
  25. package/dist/install-W9ghhGoh.d.ts +36 -0
  26. package/dist/installed-B-PfERBU.js +30 -0
  27. package/dist/invariant-D8_xBqmZ.js +22 -0
  28. package/dist/migrate-B0k_0swk.d.ts +54 -0
  29. package/dist/migrate-BDQ8xqUs.js +289 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-0B0QTVWX.d.ts → operations-D4A1Fcgf.d.ts} +37 -15
  32. package/dist/operations-DMMIfYPW.js +1159 -0
  33. package/dist/operations-GLeOqgMt.d.ts +257 -0
  34. package/dist/operations.d.ts +3 -7
  35. package/dist/operations.js +3 -2
  36. package/dist/overlay/client-DmsSMOzi.js +4 -0
  37. package/dist/overlay/dist-BoHMOFax.js +14 -0
  38. package/dist/overlay/dist-yIZmvSaU.js +1 -0
  39. package/dist/overlay/overlay.js +183 -177
  40. package/dist/page/loader.js +138 -18
  41. package/dist/{page-BuroSMXO.js → page-B41ozN63.js} +8 -6
  42. package/dist/{page-BtXADR6d.d.ts → page-DtbMOEMd.d.ts} +6 -5
  43. package/dist/page-tools-shared-NHUjKI8E.js +117 -0
  44. package/dist/path--zk6PEMz.js +18 -0
  45. package/dist/plugin-PS8PMYus.js +74 -0
  46. package/dist/realtime.d.ts +6 -12
  47. package/dist/realtime.js +23 -24
  48. package/dist/rpc-HBcWtg0T.d.ts +17 -0
  49. package/dist/rpc-RKPAusHp.js +153 -0
  50. package/dist/rpc.d.ts +2 -29
  51. package/dist/rpc.js +2 -75
  52. package/dist/runtime/auth.d.ts +5 -3
  53. package/dist/runtime/auth.js +8 -5
  54. package/dist/runtime/console.d.ts +1 -1
  55. package/dist/runtime/console.js +26 -21
  56. package/dist/runtime/index.d.ts +108 -60
  57. package/dist/runtime/index.js +684 -236
  58. package/dist/{server-BomGg3Gb.js → server-D8k-0GXe.js} +16 -7
  59. package/dist/server.d.ts +14 -88
  60. package/dist/server.js +7 -326
  61. package/dist/service-CFVm23k7.d.ts +158 -0
  62. package/dist/service-GHhhyQj4.js +609 -0
  63. package/dist/session-DVx-1Tym.d.ts +14 -0
  64. package/dist/session-EkudzUmm.js +503 -0
  65. package/dist/testing.d.ts +1 -1
  66. package/dist/testing.js +14 -2
  67. package/dist/tokens-DSbwkVSy.js +58 -0
  68. package/dist/types-BIS0hCEl.d.ts +124 -0
  69. package/dist/types-CZujrMFd.d.ts +322 -0
  70. package/dist/vite.d.ts +91 -87
  71. package/dist/vite.js +535 -796
  72. package/package.json +24 -27
  73. package/dist/database-BSnVrwHn.js +0 -60
  74. package/dist/database-C-ktS9Do.js +0 -95
  75. package/dist/define-BzW2Ychn.d.ts +0 -46
  76. package/dist/define-Cbhl6QVJ.js +0 -32
  77. package/dist/errors-BAQYcy3_.d.ts +0 -89
  78. package/dist/errors-DeD6wTCl.js +0 -77
  79. package/dist/h3-v1-request-DDGXJ9E7.js +0 -166
  80. package/dist/index-DklG2Etf.d.ts +0 -111
  81. package/dist/operations-NZG5dB8y.js +0 -732
  82. package/dist/page-tools-shared-D-amu6sx.js +0 -53
  83. package/dist/plugin-QElKQYkA.js +0 -725
  84. package/dist/request-DVc3M_AG.js +0 -14
  85. package/dist/src-CRTwnaEG.js +0 -1362
  86. package/dist/types-Cj8K7Vx7.d.ts +0 -176
  87. package/dist/types-Un2dcJWD.d.ts +0 -288
@@ -0,0 +1,36 @@
1
+ import { d as CommentsPeople } from "./define-B3TF9zzn.js";
2
+ import { a as commentsSchema } from "./database-CA1aHKN7.js";
3
+ import { r as CommentsSchemaOwner } from "./migrate-B0k_0swk.js";
4
+ import { t as Comments } from "./index-DNhy69Wt.js";
5
+ import { c as CommentsTables, i as CommentsRuntime, n as CommentsAttachmentStore, o as CommentsDatabase, u as SharedRateLimit } from "./service-CFVm23k7.js";
6
+ //#region src/install.d.ts
7
+ interface InstallCommentsOptions {
8
+ database: CommentsDatabase;
9
+ /** The tables of the Database schema, so a Postgres Database uses its own. Default: the SQLite tables. */
10
+ tables?: CommentsTables & {
11
+ commentForge?: typeof commentsSchema.vitehubCommentForge;
12
+ };
13
+ /** The Auth adapter for `@` suggestions, when the app has Auth and no `people`. */
14
+ users?: CommentsPeople;
15
+ /** The Blob store for attachments, when the app has one and no `storeAttachment`. */
16
+ attachments?: CommentsAttachmentStore;
17
+ /** `checkRateLimit` of ViteHub Rate Limit, when it counts in a shared KV store. See `CommentsRuntime.rateLimit`. */
18
+ rateLimit?: SharedRateLimit;
19
+ /** Only the Vite dev server enables it, for the default guest policy. Without it, the operation context decides, else `false`. */
20
+ development?: boolean;
21
+ /**
22
+ * Who keeps the tables up to date. `"comments"`: Comments opened the Database itself, so it migrates and creates
23
+ * the tables before the first query. Default `"app"`: the app's migrations do, and Comments fails with
24
+ * `COMMENTS_R0019` until the tables match this version. See `CommentsSchemaOwner`.
25
+ */
26
+ schema?: CommentsSchemaOwner;
27
+ /** The SQL dialect of `database`. Default `sqlite`: SQLite, libSQL, and D1. */
28
+ dialect?: "sqlite" | "postgresql";
29
+ }
30
+ /**
31
+ * Connects a Comments definition to its Database, for the server API, the overlay API, and the comment operations.
32
+ * The generated Nitro plugin calls it on the first Comments call; call it yourself only in tests or outside ViteHub.
33
+ */
34
+ declare function installComments(comments: Comments, install: InstallCommentsOptions): CommentsRuntime;
35
+ //#endregion
36
+ export { installComments as n, InstallCommentsOptions as t };
@@ -0,0 +1,30 @@
1
+ import { r as hasCommentsRuntime, t as commentsRuntime } from "./server-D8k-0GXe.js";
2
+ //#region src/installed.ts
3
+ /** The runtime that `installComments()` connected to each definition. */
4
+ const runtimes = /* @__PURE__ */ new WeakMap();
5
+ /** The runtime that the generated Nitro plugin builds on the first call, per definition. */
6
+ const runtimeBuilds = /* @__PURE__ */ new WeakMap();
7
+ const pendingKey = Symbol.for("vitehub.comments.pending");
8
+ /**
9
+ * The runtime of a definition. The generated Nitro plugin builds it on the first call, so a server API call before
10
+ * any operation builds it too.
11
+ */
12
+ async function runtimeOf(comments) {
13
+ const installed = runtimes.get(comments)?.runtime;
14
+ if (installed) return installed;
15
+ const build = runtimeBuilds.get(comments);
16
+ if (build) return await build().catch(() => void 0);
17
+ if (!hasCommentsRuntime()) return void 0;
18
+ const built = await commentsRuntime().catch(() => void 0);
19
+ return built?.definition === comments.options ? built : void 0;
20
+ }
21
+ /** The runtime that `installComments()` connected, for the overlay API and the MCP tools. */
22
+ function commentsRuntimeOf(comments) {
23
+ return runtimes.get(comments)?.runtime;
24
+ }
25
+ /** The runtime of a definition, or the one that the generated Nitro plugin builds on first use, for the overlay API. */
26
+ async function resolveCommentsRuntime(comments) {
27
+ return runtimeOf(comments);
28
+ }
29
+ //#endregion
30
+ export { runtimeOf as a, runtimeBuilds as i, pendingKey as n, runtimes as o, resolveCommentsRuntime as r, commentsRuntimeOf as t };
@@ -0,0 +1,22 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ export { invariant as t };
@@ -0,0 +1,54 @@
1
+ //#region src/migrate.d.ts
2
+ /**
3
+ * - `empty`: no `vitehub_comment_threads` table.
4
+ * - `live`: the tables of the live-site model: threads with `number`, `page`, and `created_by`, and `vitehub_comments`.
5
+ * - `outdated`: the tables of one model, without columns that a later version added.
6
+ * - `current`: nothing to do.
7
+ */
8
+ type CommentsSchemaState = "empty" | "live" | "outdated" | "current";
9
+ interface CommentsMigrationOptions {
10
+ /** `postgresql` for a Postgres Database. Default `sqlite`: SQLite, libSQL, and D1. */
11
+ dialect?: "sqlite" | "postgresql";
12
+ }
13
+ interface CommentsMigration {
14
+ /** What the Database had before. */
15
+ from: CommentsSchemaState;
16
+ /** The statements that ran. Empty when there was nothing to do. */
17
+ statements: string[];
18
+ /** The table that keeps the threads of the live-site model, after a `live` migration. */
19
+ backup?: string;
20
+ }
21
+ /** The live-site threads, after the migration renames them. The migration never deletes them. */
22
+ declare const liveThreadsBackup = "vitehub_comment_threads_live";
23
+ /**
24
+ * The SQL of a migration, to put in a custom migration file: `vitehub database generate --custom`, or
25
+ * `wrangler d1 execute --file`. `from: "live"` moves the live-site tables of SQLite, libSQL, or D1 to one model;
26
+ * `from: "outdated"` adds the columns of this version, on SQLite or Postgres. Run each SQL once. `migrateComments()`
27
+ * reads the Database first, so it can run on every deploy.
28
+ */
29
+ declare function commentsMigrationSql(options: CommentsMigrationOptions & {
30
+ from: "live" | "outdated";
31
+ missing?: readonly string[];
32
+ }): string[];
33
+ /** What the Database has: no comments yet, the live-site tables, one model without newer columns, or nothing to do. */
34
+ declare function commentsSchemaState(db: object, options?: CommentsMigrationOptions): Promise<{
35
+ state: CommentsSchemaState;
36
+ missing: string[];
37
+ }>;
38
+ /**
39
+ * Brings the comment tables of a Database to this version, in place. It reads the tables first, so a second run does
40
+ * nothing. A live-site Database keeps its old tables: the threads move to `vitehub_comment_threads_live`, and
41
+ * `vitehub_comments` and `vitehub_comment_scope_counters` stay. All statements run in one batch or transaction, so a
42
+ * failure changes nothing. Stop comment writes while it runs, and back up the Database first.
43
+ */
44
+ declare function migrateComments(db: object, options?: CommentsMigrationOptions): Promise<CommentsMigration>;
45
+ /**
46
+ * Who keeps the comment tables of a Database up to date.
47
+ * - `comments`: Comments opened the Database itself, such as the SQLite file or D1 binding of `comments()`. Before the
48
+ * first query of each process it runs `migrateComments()` and creates the tables that are missing.
49
+ * - `app`: the app's migrations do, as with a ViteHub Database. Before the first query of each process Comments reads
50
+ * the tables, and fails with `COMMENTS_R0019` until a migration brings them to this version.
51
+ */
52
+ type CommentsSchemaOwner = "comments" | "app";
53
+ //#endregion
54
+ export { commentsMigrationSql as a, migrateComments as c, CommentsSchemaState as i, CommentsMigrationOptions as n, commentsSchemaState as o, CommentsSchemaOwner as r, liveThreadsBackup as s, CommentsMigration as t };
@@ -0,0 +1,289 @@
1
+ import { t as commentsErrorDiagnostics } from "./errors-C6qptPoG.js";
2
+ import { sql } from "drizzle-orm";
3
+ import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
4
+ //#region src/operations-core/database.ts
5
+ /**
6
+ * Threads of comments. `n` is unique inside `scope`, which is what `?comment=<n>` names. `anchor`, `actor`,
7
+ * `resolvedBy`, `metadata`, and `context` hold JSON. Times are milliseconds since the epoch.
8
+ */
9
+ const commentThreads = sqliteTable("vitehub_comment_threads", {
10
+ id: text("id").primaryKey(),
11
+ scope: text("scope").notNull(),
12
+ n: integer("n").notNull(),
13
+ subjectKind: text("subject_kind").notNull(),
14
+ subjectId: text("subject_id").notNull(),
15
+ anchor: text("anchor").notNull(),
16
+ status: text("status", { enum: ["open", "resolved"] }).notNull(),
17
+ resolvedBy: text("resolved_by"),
18
+ resolvedAt: integer("resolved_at"),
19
+ authorId: text("author_id").notNull(),
20
+ authorName: text("author_name"),
21
+ authorImage: text("author_image"),
22
+ actor: text("actor"),
23
+ /** JSON of the fields that app code keeps on the thread. */
24
+ metadata: text("metadata"),
25
+ /** JSON of the page, element, components, browser, and build that the overlay read. */
26
+ context: text("context"),
27
+ /** The version of the subject that the thread was started on. */
28
+ revision: integer("revision"),
29
+ /** The retry key of `comments.create`. Unique inside `scope`. */
30
+ requestId: text("request_id"),
31
+ createdAt: integer("created_at").notNull(),
32
+ updatedAt: integer("updated_at").notNull()
33
+ }, (table) => [
34
+ uniqueIndex("vitehub_comment_threads_scope_n").on(table.scope, table.n),
35
+ uniqueIndex("vitehub_comment_threads_scope_request").on(table.scope, table.requestId),
36
+ index("vitehub_comment_threads_subject").on(table.subjectKind, table.subjectId),
37
+ index("vitehub_comment_threads_status").on(table.status, table.updatedAt)
38
+ ]);
39
+ /** One Markdown message. The first message of a thread is the comment. `mentions` and `attachments` hold JSON lists. */
40
+ const commentMessages = sqliteTable("vitehub_comment_messages", {
41
+ id: text("id").primaryKey(),
42
+ threadId: text("thread_id").notNull(),
43
+ body: text("body").notNull(),
44
+ authorId: text("author_id").notNull(),
45
+ authorName: text("author_name"),
46
+ authorImage: text("author_image"),
47
+ actor: text("actor"),
48
+ mentions: text("mentions").notNull(),
49
+ attachments: text("attachments").notNull(),
50
+ createdAt: integer("created_at").notNull(),
51
+ editedAt: integer("edited_at")
52
+ }, (table) => [index("vitehub_comment_messages_thread").on(table.threadId, table.createdAt)]);
53
+ /**
54
+ * The next thread number of each scope. A number is handed out once, so a deleted thread never gives its number to a
55
+ * new one, and a link such as `?comment=3` keeps naming the same thread.
56
+ */
57
+ const commentCounters = sqliteTable("vitehub_comment_counters", {
58
+ scope: text("scope").primaryKey(),
59
+ next: integer("next").notNull()
60
+ });
61
+ /**
62
+ * The pull request comment of each message, when `defineComments({ forge })` posts threads. `id` is a message id,
63
+ * `summary:<repository>#<pull request>`, or `cleanup:<repository>#<remote id>` for a pending delete.
64
+ */
65
+ const commentForge = sqliteTable("vitehub_comment_forge", {
66
+ id: text("id").primaryKey(),
67
+ /** Null for summaries and cleanup rows, which survive deletion of the original thread. */
68
+ threadId: text("thread_id"),
69
+ repository: text("repository").notNull(),
70
+ pullRequest: integer("pull_request").notNull(),
71
+ /** The forge's id of the comment. Null until it posts. */
72
+ remoteId: text("remote_id"),
73
+ /** The GraphQL id, to hide the comment of a resolved thread. */
74
+ nodeId: text("node_id"),
75
+ url: text("url"),
76
+ /** Hash of the body the forge has, so an unchanged comment is not sent again. */
77
+ digest: text("digest"),
78
+ postedAs: text("posted_as", { enum: ["author", "app"] }),
79
+ /** Whether the forge hides the comment, because its thread is resolved. */
80
+ minimized: integer("minimized", { mode: "boolean" }).notNull().default(false),
81
+ error: text("error"),
82
+ updatedAt: integer("updated_at").notNull()
83
+ }, (table) => [index("vitehub_comment_forge_thread").on(table.threadId), index("vitehub_comment_forge_pull_request").on(table.repository, table.pullRequest)]);
84
+ /**
85
+ * The tables of Comments, for SQLite, libSQL, and D1. ViteHub adds them to the Database for you; add them to a
86
+ * Database Definition yourself only without ViteHub. For Postgres use `@vite-hub/comments/database/postgres`. The keys
87
+ * carry the prefix too: ViteHub merges them into the app's Database schema, which may have its own `commentThreads`.
88
+ */
89
+ const commentsSchema = {
90
+ vitehubCommentThreads: commentThreads,
91
+ vitehubCommentMessages: commentMessages,
92
+ vitehubCommentCounters: commentCounters,
93
+ vitehubCommentForge: commentForge
94
+ };
95
+ //#endregion
96
+ //#region src/tables.ts
97
+ /**
98
+ * The tables of `commentsSchema` as SQLite statements that are safe to run on every start. A database that Comments
99
+ * opens itself gets them on first use; a ViteHub Database gets the same tables from `vitehub database generate` instead.
100
+ * A database that still has the tables of the live-site model needs `migrateComments()` first; `installComments()`
101
+ * runs it with `schema: "comments"`.
102
+ */
103
+ const commentsTables = [
104
+ "CREATE TABLE IF NOT EXISTS `vitehub_comment_threads` (`id` text PRIMARY KEY NOT NULL, `scope` text NOT NULL, `n` integer NOT NULL, `subject_kind` text NOT NULL, `subject_id` text NOT NULL, `anchor` text NOT NULL, `status` text NOT NULL, `resolved_by` text, `resolved_at` integer, `author_id` text NOT NULL, `author_name` text, `author_image` text, `actor` text, `metadata` text, `context` text, `revision` integer, `request_id` text, `created_at` integer NOT NULL, `updated_at` integer NOT NULL)",
105
+ "CREATE UNIQUE INDEX IF NOT EXISTS `vitehub_comment_threads_scope_n` ON `vitehub_comment_threads` (`scope`,`n`)",
106
+ "CREATE UNIQUE INDEX IF NOT EXISTS `vitehub_comment_threads_scope_request` ON `vitehub_comment_threads` (`scope`,`request_id`)",
107
+ "CREATE INDEX IF NOT EXISTS `vitehub_comment_threads_subject` ON `vitehub_comment_threads` (`subject_kind`,`subject_id`)",
108
+ "CREATE INDEX IF NOT EXISTS `vitehub_comment_threads_status` ON `vitehub_comment_threads` (`status`,`updated_at`)",
109
+ "CREATE TABLE IF NOT EXISTS `vitehub_comment_messages` (`id` text PRIMARY KEY NOT NULL, `thread_id` text NOT NULL, `body` text NOT NULL, `author_id` text NOT NULL, `author_name` text, `author_image` text, `actor` text, `mentions` text NOT NULL, `attachments` text NOT NULL, `created_at` integer NOT NULL, `edited_at` integer)",
110
+ "CREATE INDEX IF NOT EXISTS `vitehub_comment_messages_thread` ON `vitehub_comment_messages` (`thread_id`,`created_at`)",
111
+ "CREATE TABLE IF NOT EXISTS `vitehub_comment_counters` (`scope` text PRIMARY KEY NOT NULL, `next` integer NOT NULL)",
112
+ "CREATE TABLE IF NOT EXISTS `vitehub_comment_forge` (`id` text PRIMARY KEY NOT NULL, `thread_id` text, `repository` text NOT NULL, `pull_request` integer NOT NULL, `remote_id` text, `node_id` text, `url` text, `digest` text, `posted_as` text, `minimized` integer DEFAULT false NOT NULL, `error` text, `updated_at` integer NOT NULL)",
113
+ "CREATE INDEX IF NOT EXISTS `vitehub_comment_forge_thread` ON `vitehub_comment_forge` (`thread_id`)",
114
+ "CREATE INDEX IF NOT EXISTS `vitehub_comment_forge_pull_request` ON `vitehub_comment_forge` (`repository`,`pull_request`)"
115
+ ];
116
+ //#endregion
117
+ //#region src/migrate.ts
118
+ /** The live-site threads, after the migration renames them. The migration never deletes them. */
119
+ const liveThreadsBackup = "vitehub_comment_threads_live";
120
+ /** The columns that one model added to `vitehub_comment_threads` after its first version. */
121
+ const addedColumns = {
122
+ metadata: "text",
123
+ context: "text",
124
+ revision: "integer",
125
+ request_id: "text"
126
+ };
127
+ /** The unique index of the `comments.create` retry key, which came with `request_id`. */
128
+ const requestIndex = commentsTables.find((statement) => statement.includes("`vitehub_comment_threads_scope_request`"));
129
+ const scopeOf = "CASE WHEN `scope` = 'pages' THEN 'site' ELSE `scope` END";
130
+ function migratedAuthorId(column) {
131
+ const id = `json_extract(${column}, '$.id')`;
132
+ return `CASE WHEN json_extract(${column}, '$.guest') = 1 AND substr(${id}, 1, 6) <> 'guest:' THEN 'guest:' || ${id} ELSE ${id} END`;
133
+ }
134
+ /**
135
+ * Moves the live-site tables to the tables of one model, on SQLite, libSQL, and D1. It renames the threads table to
136
+ * `vitehub_comment_threads_live`, creates the new tables, and copies every thread and comment. It deletes nothing:
137
+ * `vitehub_comment_threads_live`, `vitehub_comments`, and `vitehub_comment_scope_counters` stay for you to check.
138
+ */
139
+ function liveToCurrent() {
140
+ const subjectKind = "CASE WHEN `scope` = 'pages' THEN 'page' WHEN instr(`scope`, ':') > 1 THEN substr(`scope`, 1, instr(`scope`, ':') - 1) ELSE `scope` END";
141
+ const subjectId = "CASE WHEN `scope` = 'pages' THEN `page` WHEN instr(`scope`, ':') > 1 THEN substr(`scope`, instr(`scope`, ':') + 1) ELSE `page` END";
142
+ const siteLast = `max(coalesce((SELECT max(\`number\`) FROM \`${liveThreadsBackup}\` WHERE \`scope\` = 'site'), 0), coalesce((SELECT \`last_number\` FROM \`vitehub_comment_scope_counters\` WHERE \`scope\` = 'site'), 0))`;
143
+ const numberOf = (column) => `${column} + CASE WHEN \`scope\` = 'pages' THEN ${siteLast} ELSE 0 END`;
144
+ return [
145
+ `ALTER TABLE \`vitehub_comment_threads\` RENAME TO \`${liveThreadsBackup}\``,
146
+ ...commentsTables,
147
+ "CREATE TABLE IF NOT EXISTS `vitehub_comment_scope_counters` (`scope` text PRIMARY KEY NOT NULL, `last_number` integer NOT NULL)",
148
+ [
149
+ "INSERT INTO `vitehub_comment_threads` (`id`, `scope`, `n`, `subject_kind`, `subject_id`, `anchor`, `status`, `resolved_by`, `resolved_at`, `author_id`, `author_name`, `author_image`, `actor`, `metadata`, `context`, `revision`, `created_at`, `updated_at`)",
150
+ `SELECT \`id\`, ${scopeOf}, ${numberOf("`number`")}, ${subjectKind}, ${subjectId},`,
151
+ "CASE WHEN `anchor` IS NULL OR `anchor` = 'null' THEN '{\"kind\":\"page\"}' ELSE json_set(`anchor`, '$.kind', 'element') END,",
152
+ "`status`, `resolved_by`, `resolved_at`,",
153
+ `${migratedAuthorId("`created_by`")}, json_extract(\`created_by\`, '$.name'), json_extract(\`created_by\`, '$.image'),`,
154
+ "NULL, `metadata`, `context`, NULL, `created_at`, `updated_at`",
155
+ `FROM \`${liveThreadsBackup}\``
156
+ ].join(" "),
157
+ [
158
+ "INSERT INTO `vitehub_comment_messages` (`id`, `thread_id`, `body`, `author_id`, `author_name`, `author_image`, `actor`, `mentions`, `attachments`, `created_at`, `edited_at`)",
159
+ `SELECT \`c\`.\`id\`, \`c\`.\`thread_id\`, \`c\`.\`body\`, ${migratedAuthorId("`c`.`author`")}, json_extract(\`c\`.\`author\`, '$.name'), json_extract(\`c\`.\`author\`, '$.image'), NULL,`,
160
+ "coalesce((SELECT json_group_array(json_extract(`m`.`value`, '$.id')) FROM json_each(`c`.`mentions`) AS `m`), '[]'), '[]', `c`.`created_at`, `c`.`edited_at`",
161
+ `FROM \`vitehub_comments\` AS \`c\` WHERE \`c\`.\`thread_id\` IN (SELECT \`id\` FROM \`${liveThreadsBackup}\`)`
162
+ ].join(" "),
163
+ `INSERT INTO \`vitehub_comment_counters\` (\`scope\`, \`next\`) SELECT ${scopeOf}, max(${numberOf("`number`")}) + 1 FROM \`${liveThreadsBackup}\` GROUP BY 1 ON CONFLICT (\`scope\`) DO UPDATE SET \`next\` = max(\`next\`, excluded.\`next\`)`,
164
+ `INSERT INTO \`vitehub_comment_counters\` (\`scope\`, \`next\`) SELECT ${scopeOf}, ${numberOf("`last_number`")} + 1 FROM \`vitehub_comment_scope_counters\` WHERE true ON CONFLICT (\`scope\`) DO UPDATE SET \`next\` = max(\`next\`, excluded.\`next\`)`
165
+ ];
166
+ }
167
+ function postgresCurrent() {
168
+ return [
169
+ ...Object.entries(addedColumns).map(([column, type]) => `ALTER TABLE "vitehub_comment_threads" ADD COLUMN IF NOT EXISTS "${column}" ${type === "integer" ? "bigint" : type}`),
170
+ requestIndex.replaceAll("`", "\""),
171
+ "CREATE TABLE IF NOT EXISTS \"vitehub_comment_forge\" (\"id\" text PRIMARY KEY NOT NULL, \"thread_id\" text, \"repository\" text NOT NULL, \"pull_request\" bigint NOT NULL, \"remote_id\" text, \"node_id\" text, \"url\" text, \"digest\" text, \"posted_as\" text, \"minimized\" boolean DEFAULT false NOT NULL, \"error\" text, \"updated_at\" bigint NOT NULL)",
172
+ "CREATE INDEX IF NOT EXISTS \"vitehub_comment_forge_thread\" ON \"vitehub_comment_forge\" (\"thread_id\")",
173
+ "CREATE INDEX IF NOT EXISTS \"vitehub_comment_forge_pull_request\" ON \"vitehub_comment_forge\" (\"repository\",\"pull_request\")"
174
+ ];
175
+ }
176
+ /**
177
+ * The SQL of a migration, to put in a custom migration file: `vitehub database generate --custom`, or
178
+ * `wrangler d1 execute --file`. `from: "live"` moves the live-site tables of SQLite, libSQL, or D1 to one model;
179
+ * `from: "outdated"` adds the columns of this version, on SQLite or Postgres. Run each SQL once. `migrateComments()`
180
+ * reads the Database first, so it can run on every deploy.
181
+ */
182
+ function commentsMigrationSql(options) {
183
+ if (options.dialect === "postgresql") {
184
+ if (options.from === "live") throw commentsErrorDiagnostics.COMMENTS_MIGRATION_LIVE_POSTGRES();
185
+ return postgresCurrent();
186
+ }
187
+ if (options.from === "live") return liveToCurrent();
188
+ const missing = options.missing ?? Object.keys(addedColumns);
189
+ return [
190
+ ...Object.entries(addedColumns).filter(([column]) => missing.includes(column)).map(([column, type]) => `ALTER TABLE \`vitehub_comment_threads\` ADD COLUMN \`${column}\` ${type}`),
191
+ requestIndex,
192
+ ...commentsTables.filter((statement) => statement.includes("vitehub_comment_forge"))
193
+ ];
194
+ }
195
+ /** Keep synchronous transaction callbacks synchronous, so their driver can roll back a later failure. */
196
+ function runSqliteStatements(db, statements, start = 0) {
197
+ for (let index = start; index < statements.length; index++) {
198
+ const result = db.run(sql.raw(statements[index]));
199
+ if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") return Promise.resolve(result).then(() => runSqliteStatements(db, statements, index + 1));
200
+ }
201
+ }
202
+ /** The first column of each row: libSQL and D1 return objects, the SQLite proxy returns arrays. */
203
+ function names(rows) {
204
+ return (Array.isArray(rows) ? rows : Array.isArray(Reflect.get(Object(rows), "rows")) ? Reflect.get(Object(rows), "rows") : []).map((row) => String(Array.isArray(row) ? row[0] : Object.values(Object(row))[0]));
205
+ }
206
+ async function columns(db, postgres) {
207
+ if (postgres) return names(await db.execute(sql.raw("SELECT column_name FROM information_schema.columns WHERE table_name = 'vitehub_comment_threads' AND table_schema = current_schema()")));
208
+ return names(await db.all(sql.raw("SELECT name FROM pragma_table_info('vitehub_comment_threads')")));
209
+ }
210
+ /** What the Database has: no comments yet, the live-site tables, one model without newer columns, or nothing to do. */
211
+ async function commentsSchemaState(db, options = {}) {
212
+ const found = await columns(db, options.dialect === "postgresql");
213
+ if (!found.length) return {
214
+ missing: [],
215
+ state: "empty"
216
+ };
217
+ if (found.includes("number") && found.includes("created_by")) return {
218
+ missing: [],
219
+ state: "live"
220
+ };
221
+ const missing = Object.keys(addedColumns).filter((column) => !found.includes(column));
222
+ return {
223
+ missing,
224
+ state: missing.length ? "outdated" : "current"
225
+ };
226
+ }
227
+ /**
228
+ * Brings the comment tables of a Database to this version, in place. It reads the tables first, so a second run does
229
+ * nothing. A live-site Database keeps its old tables: the threads move to `vitehub_comment_threads_live`, and
230
+ * `vitehub_comments` and `vitehub_comment_scope_counters` stay. All statements run in one batch or transaction, so a
231
+ * failure changes nothing. Stop comment writes while it runs, and back up the Database first.
232
+ */
233
+ async function migrateComments(db, options = {}) {
234
+ const target = db;
235
+ const postgres = options.dialect === "postgresql";
236
+ const { state, missing } = await commentsSchemaState(target, options);
237
+ if (state === "empty" || state === "current") return {
238
+ from: state,
239
+ statements: []
240
+ };
241
+ const statements = commentsMigrationSql({
242
+ ...options,
243
+ from: state,
244
+ missing
245
+ });
246
+ if (postgres) {
247
+ if (!target.transaction) throw commentsErrorDiagnostics.COMMENTS_MIGRATION_DATABASE_UNSUPPORTED({ dialect: "postgresql" });
248
+ await target.transaction(async (tx) => {
249
+ for (const statement of statements) await tx.execute(sql.raw(statement));
250
+ });
251
+ } else if (target.batch) await target.batch(statements.map((statement) => target.run(sql.raw(statement))));
252
+ else if (target.transaction) await target.transaction((tx) => runSqliteStatements(tx, statements));
253
+ else throw commentsErrorDiagnostics.COMMENTS_MIGRATION_DATABASE_UNSUPPORTED({ dialect: "sqlite" });
254
+ return {
255
+ from: state,
256
+ statements,
257
+ ...state === "live" ? { backup: liveThreadsBackup } : {}
258
+ };
259
+ }
260
+ /**
261
+ * A function that the store awaits before each query: it prepares or checks the tables once per process. A failure
262
+ * is not kept, so the next query tries again, and a Database that a migration fixed works without a restart.
263
+ */
264
+ function commentsSchemaGate(db, owner, options = {}) {
265
+ let ready;
266
+ async function prepare() {
267
+ if (owner === "comments") {
268
+ await migrateComments(db, options);
269
+ const target = db;
270
+ if (target.batch) await target.batch(commentsTables.map((statement) => target.run(sql.raw(statement))));
271
+ else await runSqliteStatements(target, [...commentsTables]);
272
+ return;
273
+ }
274
+ const { state, missing } = await commentsSchemaState(db, options);
275
+ if (state !== "current") throw Object.assign(commentsErrorDiagnostics.COMMENTS_R0019({
276
+ state,
277
+ missing
278
+ }), { status: 503 });
279
+ }
280
+ return () => {
281
+ ready ??= prepare().catch((error) => {
282
+ ready = void 0;
283
+ throw error;
284
+ });
285
+ return ready;
286
+ };
287
+ }
288
+ //#endregion
289
+ export { migrateComments as a, commentForge as c, commentsSchema as d, liveThreadsBackup as i, commentMessages as l, commentsSchemaGate as n, commentsTables as o, commentsSchemaState as r, commentCounters as s, commentsMigrationSql as t, commentThreads as u };
@@ -0,0 +1,11 @@
1
+ //#region ../internal/src/object.ts
2
+ /** A non-null object that is not an array. Functions do not pass. */
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** A non-null object or a function that is not an array. */
7
+ function isRecordOrFunction(value) {
8
+ return Object(value) === value && !Array.isArray(value);
9
+ }
10
+ //#endregion
11
+ export { isRecordOrFunction as n, isRecord as t };
@@ -1,5 +1,5 @@
1
1
  import { StandardSchemaV1 } from "@standard-schema/spec";
2
- //#region ../internal/src/operations.d.ts
2
+ //#region ../internal/src/operation-definition.d.ts
3
3
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
4
4
  type OperationKind = "read" | "write" | "destructive";
5
5
  /** The signed-in user of a call. */
@@ -22,7 +22,9 @@ interface OperationAccess {
22
22
  readonly mode: string;
23
23
  /**
24
24
  * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
25
- * operation of the section) or `"<section>:read"` (only the operations that read).
25
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
26
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
27
+ * allows only the reads of that scope.
26
28
  */
27
29
  readonly sections: "all" | readonly string[];
28
30
  readonly user?: OperationUser;
@@ -40,6 +42,12 @@ interface OperationContext {
40
42
  env?: Record<string, unknown>;
41
43
  waitUntil?: (task: Promise<unknown>) => void;
42
44
  request?: Request;
45
+ /**
46
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
47
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
48
+ * of Comments.
49
+ */
50
+ event?: unknown;
43
51
  /** Operations set a success status here, such as 202 for an accepted call. */
44
52
  response?: {
45
53
  status?: number;
@@ -62,9 +70,16 @@ interface OperationDefinition<Input, Output> {
62
70
  description: string;
63
71
  /**
64
72
  * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
65
- * from the input, for operations that serve several sections.
73
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
74
+ * scope and read-only grants. A function that returns an invalid id denies the call.
66
75
  */
67
76
  section: string | false | ((input: Input) => string | undefined);
77
+ /**
78
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
79
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
80
+ * `:` needs the whole section.
81
+ */
82
+ scope?: (input: Input) => string | undefined;
68
83
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
69
84
  kind: OperationKind;
70
85
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
@@ -73,19 +88,14 @@ interface OperationDefinition<Input, Output> {
73
88
  cli?: {
74
89
  /** Defaults: namespace = section, command = verb. */
75
90
  namespace?: string;
91
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
76
92
  command?: string;
77
93
  /** Input keys read from positional arguments, in order. */
78
94
  positional?: string[];
79
95
  /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
80
96
  format?: (output: Output) => string;
81
- /** `vitehub <namespace>` runs this command when no command is named, such as `vitehub usage`. */
97
+ /** `vitehub <namespace>` runs this command when no command is named. */
82
98
  default?: boolean;
83
- /**
84
- * Route of the app that takes a signed dispatch of this operation, such as `/_vitehub/schedules/run`. With `--url`
85
- * and a dispatch key in the environment (`VITEHUB_DISPATCH_KEY`), the command signs the input and posts it there, so
86
- * a CI job needs no Console credentials. Without a key it calls the RPC.
87
- */
88
- dispatch?: string;
89
99
  };
90
100
  /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
91
101
  maxRequestBytes?: number;
@@ -94,8 +104,16 @@ interface OperationDefinition<Input, Output> {
94
104
  * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
95
105
  */
96
106
  readOnlyWhen?: (input: Input) => boolean;
97
- /** `false`: MCP does not offer the operation as a tool, such as an editor transport that only the Console uses. */
98
- mcp?: false;
107
+ /**
108
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
109
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
110
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
111
+ * is the result as JSON.
112
+ */
113
+ mcp?: false | {
114
+ title?: string;
115
+ format?: (output: NoInfer<Output>) => string;
116
+ };
99
117
  /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
100
118
  user?: false;
101
119
  /**
@@ -106,24 +124,28 @@ interface OperationDefinition<Input, Output> {
106
124
  run: (input: Input, context: OperationContext) => Output | Promise<Output>;
107
125
  }
108
126
  /** An operation of any input and output, as a registry holds it. */
109
- interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "output" | "readOnlyWhen" | "run" | "section"> {
127
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
110
128
  readOnlyWhen?: (input: never) => boolean;
111
129
  cli?: {
112
130
  namespace?: string;
113
131
  command?: string;
114
132
  default?: boolean;
115
- dispatch?: string;
116
133
  positional?: string[];
117
134
  format?: (output: never) => string;
118
135
  };
136
+ mcp?: false | {
137
+ title?: string;
138
+ format?: (output: never) => string;
139
+ };
119
140
  input: StandardSchemaV1;
120
141
  output?: StandardSchemaV1;
121
142
  run: (input: never, context: OperationContext) => unknown;
143
+ scope?: (input: never) => string | undefined;
122
144
  section: string | false | ((input: never) => string | undefined);
123
145
  }
124
146
  /** The contribution of one plugin: operations, or a module that exports them. */
125
147
  interface OperationContributionEntry {
126
- /** Module the app imports, such as `@vite-hub/content/operations`. */
148
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
127
149
  module: string;
128
150
  /** Named export that holds an operation or an array of operations. Defaults to `default`. */
129
151
  export?: string;