@vite-hub/workspace 0.4.1 → 0.5.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 (95) hide show
  1. package/README.md +62 -19
  2. package/dist/blob-database/postgres.d.ts +424 -0
  3. package/dist/blob-database/postgres.js +2 -0
  4. package/dist/blob-database-sources-DDZ1wV9w.js +9 -0
  5. package/dist/blob-database.d.ts +33 -447
  6. package/dist/blob-database.js +637 -208
  7. package/dist/checkout.js +1 -1
  8. package/dist/cloudflare.d.ts +1 -1
  9. package/dist/cloudflare.js +1 -1
  10. package/dist/{config-D1QENneP.js → config-DiyPi3Ff.js} +7 -7
  11. package/dist/{config-CDeGd0RB.d.ts → config-hxABr_Gg.d.ts} +1 -1
  12. package/dist/durability.d.ts +11 -2
  13. package/dist/durability.js +46 -4
  14. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-C0KyI408.js} +5 -1
  15. package/dist/{error-diagnostics-B5s9kNEA.js → error-diagnostics-Cth97txN.js} +10 -2
  16. package/dist/{path-uxLkzrZm.d.ts → errors-DXCZjdUU.d.ts} +0 -1
  17. package/dist/{file-CqG9zqiF.js → file-C1DYoGz3.js} +1 -1
  18. package/dist/{target-Dm9dHAVJ.js → file-metadata-Dv2JZwal.js} +1 -29
  19. package/dist/{files-B6wpAhEx.js → files-iHyik8jj.js} +2 -2
  20. package/dist/files.d.ts +13 -5
  21. package/dist/files.js +6 -5
  22. package/dist/{github-DKAlO0Vh.js → github-CFHl6RI0.js} +4 -4
  23. package/dist/{glob-BOqSKzSg.js → glob-BitxqDhb.js} +7 -7
  24. package/dist/{glob-Cjxms1t7.js → glob-Buxfvmyy.js} +1 -1
  25. package/dist/history-schema-BBWbpDk4.d.ts +436 -0
  26. package/dist/history-schema-postgres-U_ueRvmO.js +41 -0
  27. package/dist/{host-Bf1a2uo_.js → host-Dmr2Ctem.js} +150 -16
  28. package/dist/{hosted-zG7HJaE4.js → hosted-BktlvkF2.js} +20 -11
  29. package/dist/{hosted-vercel-blob-AbXG8fvR.js → hosted-vercel-blob-D0IPAjb1.js} +5 -5
  30. package/dist/hosted-vercel-blob.d.ts +1 -1
  31. package/dist/hosted-vercel-blob.js +1 -1
  32. package/dist/hosted.d.ts +1 -1
  33. package/dist/hosted.js +1 -1
  34. package/dist/index.d.ts +11 -23
  35. package/dist/index.js +28 -106
  36. package/dist/internal/workspace.d.ts +14 -0
  37. package/dist/internal/workspace.js +86 -0
  38. package/dist/{lifecycle-D8FdpBod.js → lifecycle-D6WN2dd_.js} +11 -8
  39. package/dist/loader.d.ts +1 -1
  40. package/dist/loader.js +2 -2
  41. package/dist/{mcp-resources-DntxtmDU.js → mcp-resources-TtxLNSL6.js} +1 -1
  42. package/dist/{memory-D5jq9HZW.js → memory-DjzwSng2.js} +16 -8
  43. package/dist/{metadata-target-DDoOQNp1.js → metadata-target-CR0aDtvS.js} +205 -60
  44. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CI2PJGqu.d.ts} +8 -2
  45. package/dist/{operations-D8uCpzhM.js → operations-Cib30_dt.js} +5 -5
  46. package/dist/{operations-DsY2MQnG.js → operations-dtcU5LkD.js} +22 -7
  47. package/dist/operations.d.ts +2 -2
  48. package/dist/operations.js +1 -1
  49. package/dist/{path--wrT_Azm.js → path-BlIBpI7U.js} +1 -16
  50. package/dist/{plugins-CsrXCA1Q.d.ts → plugins-DKCBrH31.d.ts} +1 -1
  51. package/dist/{provider-sm9uzkLg.js → provider-Fc3M6bEx.js} +23 -10
  52. package/dist/providers/github/store.d.ts +1 -1
  53. package/dist/providers/github/store.js +1 -1
  54. package/dist/{registry-CwryP59t.d.ts → registry-CLL0TY0L.d.ts} +5 -3
  55. package/dist/{registry-DmVfUe4K.js → registry-CedQvQxW.js} +8 -3
  56. package/dist/{registry-CFl1Htyc.d.ts → registry-DpB5PBA4.d.ts} +5 -4
  57. package/dist/{request-scope-Dw5n8bMC.js → request-scope-Bcv2kD8h.js} +2 -1
  58. package/dist/rule-keys-Bsz6jTTF.js +19 -0
  59. package/dist/rules-OHaPFopX.js +269 -0
  60. package/dist/runtime/assets.d.ts +1 -1
  61. package/dist/runtime/assets.js +3 -3
  62. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  63. package/dist/runtime/empty-registry.d.ts +2 -2
  64. package/dist/runtime/registry.d.ts +2 -2
  65. package/dist/runtime/request.js +1 -1
  66. package/dist/runtime/state.d.ts +5 -4
  67. package/dist/runtime/state.js +18 -6
  68. package/dist/runtime/workspace.d.ts +1 -1
  69. package/dist/runtime/workspace.js +1 -1
  70. package/dist/runtime.d.ts +9 -8
  71. package/dist/runtime.js +23 -16
  72. package/dist/{search-C_RfoM2j.js → search-BqNV9LnO.js} +1 -1
  73. package/dist/{server-Cd4-iCh5.js → server-CFtrOPk6.js} +5 -5
  74. package/dist/server.d.ts +2 -2
  75. package/dist/server.js +1 -1
  76. package/dist/{shared-ovXVSV3-.js → shared-BgDjxY3J.js} +14 -3
  77. package/dist/source-metadata.d.ts +2 -2
  78. package/dist/source-metadata.js +3 -3
  79. package/dist/{state-C-YtsaiJ.d.ts → state-DBV6VHS6.d.ts} +13 -21
  80. package/dist/{store-NZoRto-Y.js → store-BRMdD8Ft.js} +37 -36
  81. package/dist/{sync-CrT8zjwc.js → sync-BezGVzrW.js} +4 -4
  82. package/dist/test.d.ts +1 -1
  83. package/dist/test.js +1 -1
  84. package/dist/{types-1Z-tKK3g.d.ts → types-9DMtFjaa.d.ts} +52 -4
  85. package/dist/{use-B0o5HoBl.js → use-Dm2tbI5F.js} +15 -15
  86. package/dist/{use-CjbF8EO9.d.ts → use-Dv973swc.d.ts} +20 -28
  87. package/dist/{state-Cb_hIyAw.js → use-tools-C1qvhzme.js} +4 -17
  88. package/dist/use-tools-CMUthOdy.d.ts +12 -0
  89. package/dist/{utils-Dw-WULEZ.js → utils-C0Au2R16.js} +77 -268
  90. package/dist/vite.d.ts +32 -3
  91. package/dist/vite.js +990 -1286
  92. package/dist/vitehub-grants-C8IAl5-M.js +38 -0
  93. package/dist/{workspace-DvKu5PRa.js → workspace-CFrwWhEm.js} +18 -17
  94. package/dist/{workspace-CIXgHeyX.d.ts → workspace-Cw4ycIW-.d.ts} +1 -1
  95. package/package.json +22 -12
@@ -1,52 +1,488 @@
1
- import { n as forkMemoryWorkspaceStore, r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-D5jq9HZW.js";
2
- import { s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
- import { o as copyJsonFileMetadata, r as workspaceStoreTarget, s as copyJsonWorkspaceMetadata } from "./target-Dm9dHAVJ.js";
4
- import { a as isExcludedWorkspacePath, f as sha256, i as decodeFile, o as isWorkspaceBytes, r as contentToBytes } from "./path--wrT_Azm.js";
5
- import { t as workspaceErrorDiagnostics } from "./error-diagnostics-B5s9kNEA.js";
6
- import { d as normalizeHistoryRef, f as rejectHistoryHead, l as historyConflict, m as validateHistoryMessage, n as createSnapshotFromEntries, r as diffSnapshots, u as normalizeHistoryPath } from "./utils-Dw-WULEZ.js";
7
- import { and, desc, eq, inArray, isNotNull, lt, sql } from "drizzle-orm";
1
+ import { n as forkMemoryWorkspaceStore, r as vitehubOwnedPrefix, t as createMemoryWorkspaceStore } from "./memory-DjzwSng2.js";
2
+ import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
+ import { n as copyJsonWorkspaceMetadata, t as copyJsonFileMetadata } from "./file-metadata-Dv2JZwal.js";
4
+ import { a as isExcludedWorkspacePath, d as sha256, i as decodeFile, o as isWorkspaceBytes, r as contentToBytes } from "./path-BlIBpI7U.js";
5
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-Cth97txN.js";
6
+ import { d as normalizeHistoryPath, f as normalizeHistoryRef, g as validateHistoryMessage, m as rejectHistoryHead, n as createSnapshotFromEntries, p as readHistoryDeleteRef, r as diffSnapshots, u as historyConflict } from "./utils-C0Au2R16.js";
7
+ import { a as provideWorkspaceStoreTarget } from "./vitehub-grants-C8IAl5-M.js";
8
+ import { t as blobDatabaseSources } from "./blob-database-sources-DDZ1wV9w.js";
9
+ import { t as workspaceHistorySchema$1 } from "./history-schema-postgres-U_ueRvmO.js";
10
+ import { and, desc, eq, exists, getColumns, gte, inArray, is, isNotNull, isNull, lt, ne, notExists, sql } from "drizzle-orm";
11
+ import { PgAsyncDatabase } from "drizzle-orm/pg-core/async/db";
8
12
  import { ViteHubError } from "@vite-hub/runtime";
9
- import { index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
13
+ import { alias } from "drizzle-orm/pg-core";
14
+ import { index as index$1, integer as integer$1, primaryKey as primaryKey$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
15
+ //#region src/storage/history-index-postgres.ts
16
+ const { workspaceHistoryWorkspaces: workspaces$2, workspaceHistoryRefs: refs$2, workspaceHistoryRevisions: revisions$2, workspaceHistoryObjects: objects$2, workspaceHistoryMetadata: metadata$2 } = workspaceHistorySchema$1;
17
+ const crossRef = alias(refs$2, "cross_ref");
18
+ const { fileIndex: _fileIndex, ...revisionColumns } = getColumns(revisions$2);
19
+ function active$1(workspace) {
20
+ return sql`exists (select 1 from ${workspaces$2} where ${workspaces$2.workspace} = ${workspace} and not ${workspaces$2.deleted})`;
21
+ }
22
+ const digestOf = sql`left(${objects$2.digest}, 64)`;
23
+ function manifestDigests(where) {
24
+ return sql`(select file.value->>'digest' from ${revisions$2} cross join lateral jsonb_each(${revisions$2.fileIndex}) as file where ${where})`;
25
+ }
26
+ function textValues(values) {
27
+ return sql`(select jsonb_array_elements_text(${JSON.stringify(values)}::text::jsonb))`;
28
+ }
29
+ async function indexFiles(entries) {
30
+ return Object.fromEntries(await Promise.all(Object.entries(entries).map(async ([path, file]) => {
31
+ const canonical = JSON.stringify(file, (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, Reflect.get(value, key)])) : value);
32
+ return [JSON.stringify(path), {
33
+ digest: file.digest,
34
+ size: file.size,
35
+ fingerprint: await sha256(canonical)
36
+ }];
37
+ })));
38
+ }
39
+ async function lock(tx, workspace) {
40
+ const [row] = await tx.select({ deleted: workspaces$2.deleted }).from(workspaces$2).where(eq(workspaces$2.workspace, workspace)).for("update");
41
+ return row !== void 0 && !row.deleted;
42
+ }
43
+ async function activeKeys(db, workspace, digests) {
44
+ if (!digests.length) return [];
45
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), sql`${digestOf} in ${textValues(digests)}`))).map((row) => [row.key.slice(0, 64), row.key]);
46
+ }
47
+ /** Each write is one transaction that locks the identity row. */
48
+ function postgresHistoryIndex(db) {
49
+ return {
50
+ async claim(current, legacy) {
51
+ try {
52
+ const rows = await db.select({ workspace: workspaces$2.workspace }).from(workspaces$2).where(inArray(workspaces$2.workspace, legacy === void 0 ? [current] : [current, legacy]));
53
+ if (rows.some((row) => row.workspace === current)) return current;
54
+ if (legacy !== void 0 && rows.some((row) => row.workspace === legacy)) return legacy;
55
+ await db.insert(workspaces$2).values({ workspace: current }).onConflictDoNothing();
56
+ return current;
57
+ } catch (error) {
58
+ if ([error, error instanceof Error ? error.cause : void 0].some((value) => value instanceof Error && "code" in value && value.code === "42P01")) throw workspaceErrorDiagnostics.WORKSPACE_POSTGRES_HISTORY_SCHEMA_MISSING({ cause: error });
59
+ throw error;
60
+ }
61
+ },
62
+ async deleted(workspace) {
63
+ const [row] = await db.select({ deleted: workspaces$2.deleted }).from(workspaces$2).where(eq(workspaces$2.workspace, workspace));
64
+ return row?.deleted;
65
+ },
66
+ async ref(workspace, ref) {
67
+ const [row] = await db.select({
68
+ ref: refs$2.ref,
69
+ head: refs$2.head,
70
+ sequence: refs$2.sequence
71
+ }).from(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref), active$1(workspace)));
72
+ return row;
73
+ },
74
+ async heads(workspace) {
75
+ const heads = await db.select({
76
+ ref: refs$2.ref,
77
+ head: refs$2.head
78
+ }).from(refs$2).where(and(eq(refs$2.workspace, workspace), isNotNull(refs$2.head), active$1(workspace)));
79
+ if (!heads.length) return [];
80
+ const rows = await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.committed, true), sql`${revisions$2.id} in ${textValues(heads.map((row) => row.head))}`, active$1(workspace)));
81
+ const byId = new Map(rows.map((row) => [row.id, row]));
82
+ return heads.flatMap(({ ref, head }) => {
83
+ const revision = byId.get(head);
84
+ return revision ? [{
85
+ ref,
86
+ revision
87
+ }] : [];
88
+ });
89
+ },
90
+ async revision(workspace, id) {
91
+ const [row] = await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.id, id), eq(revisions$2.committed, true), active$1(workspace)));
92
+ return row;
93
+ },
94
+ async list(workspace, { ref, before, path, limit }) {
95
+ const previousIndex = sql`coalesce((
96
+ select previous.file_index from ${revisions$2} as previous
97
+ where previous.workspace = ${revisions$2.workspace} and previous.id = ${revisions$2.parentId} and previous.committed
98
+ ), '{}'::jsonb)`;
99
+ const encodedPath = JSON.stringify(path);
100
+ const encodedPrefix = JSON.stringify(`${path}/`).slice(0, -1);
101
+ const inPath = (key) => sql`(${key} = ${encodedPath} or starts_with(${key}, ${encodedPrefix}))`;
102
+ const pathFilter = path === void 0 ? void 0 : sql`(
103
+ exists (
104
+ select 1
105
+ from jsonb_each(${revisions$2.fileIndex}) as current_file
106
+ left join jsonb_each(${previousIndex}) as previous_file on previous_file.key = current_file.key
107
+ where ${inPath(sql`current_file.key`)}
108
+ and current_file.value is distinct from previous_file.value
109
+ )
110
+ or exists (
111
+ select 1
112
+ from jsonb_each(${previousIndex}) as previous_file
113
+ where ${inPath(sql`previous_file.key`)} and not (${revisions$2.fileIndex} ? previous_file.key)
114
+ )
115
+ )`;
116
+ return await db.select(revisionColumns).from(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref), eq(revisions$2.committed, true), before === void 0 ? void 0 : lt(revisions$2.sequence, before), pathFilter, active$1(workspace))).orderBy(desc(revisions$2.sequence)).limit(limit);
117
+ },
118
+ async usage(workspace) {
119
+ const [result] = await db.execute(sql`
120
+ select coalesce(sum(used.size), 0) as bytes, count(*) as objects from (
121
+ select distinct file.value->>'digest' as digest, (file.value->>'size')::bigint as size
122
+ from ${revisions$2} cross join lateral jsonb_each(${revisions$2.fileIndex}) as file
123
+ where ${revisions$2.workspace} = ${workspace} and ${revisions$2.committed} and ${active$1(workspace)}
124
+ ) as used
125
+ `, "objects");
126
+ return {
127
+ bytes: Number(result?.bytes ?? 0),
128
+ objects: Number(result?.objects ?? 0)
129
+ };
130
+ },
131
+ async objectKey(workspace, digest) {
132
+ const [object] = await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), eq(digestOf, digest))).limit(1);
133
+ return object?.key;
134
+ },
135
+ async register(workspace, registry) {
136
+ await db.transaction(async (tx) => {
137
+ if (!await lock(tx, workspace)) return;
138
+ const registered = new Set((await activeKeys(tx, workspace, registry.map((object) => object.digest))).map(([digest]) => digest));
139
+ const missing = registry.filter((object) => !registered.has(object.digest));
140
+ if (missing.length) await tx.execute(sql`
141
+ insert into ${objects$2} (workspace, digest, size)
142
+ select ${workspace}, key, size from jsonb_to_recordset(${JSON.stringify(missing)}::text::jsonb) as entry(key text, size bigint)
143
+ on conflict do nothing
144
+ `);
145
+ });
146
+ },
147
+ async objectKeys(workspace, digests) {
148
+ return await activeKeys(db, workspace, digests);
149
+ },
150
+ async hasObject(workspace, key) {
151
+ const [row] = await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), eq(objects$2.digest, key), gte(objects$2.size, 0))).limit(1);
152
+ return row !== void 0;
153
+ },
154
+ async publish(workspace, { revision, ifHead, ifHeads, keys, complete }) {
155
+ if (!complete) return false;
156
+ const fileIndex = await indexFiles(revision.entries);
157
+ return await db.transaction(async (tx) => {
158
+ if (!await lock(tx, workspace)) return false;
159
+ const uploaded = [...new Set(keys)];
160
+ if (uploaded.length) {
161
+ if ((await tx.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), sql`${objects$2.digest} in ${textValues(uploaded)}`, gte(objects$2.size, 0)))).length !== uploaded.length) return false;
162
+ }
163
+ await tx.insert(refs$2).values({
164
+ workspace,
165
+ ref: revision.ref
166
+ }).onConflictDoNothing();
167
+ await tx.insert(revisions$2).values({
168
+ ...revision,
169
+ fileIndex,
170
+ committed: false
171
+ }).onConflictDoNothing();
172
+ const crossHead = (ref, head) => tx.select({ ref: crossRef.ref }).from(crossRef).where(and(eq(crossRef.workspace, workspace), eq(crossRef.ref, ref), head));
173
+ if (!(await tx.update(refs$2).set({
174
+ head: revision.id,
175
+ sequence: sql`${refs$2.sequence} + 1`
176
+ }).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, revision.ref), ifHead === null ? isNull(refs$2.head) : eq(refs$2.head, ifHead), ...ifHeads.map(([ref, head]) => head === null ? notExists(crossHead(ref, isNotNull(crossRef.head))) : exists(crossHead(ref, eq(crossRef.head, head)))))).returning({ head: refs$2.head })).length) return false;
177
+ await tx.update(revisions$2).set({ committed: true }).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.id, revision.id)));
178
+ return true;
179
+ });
180
+ },
181
+ async deleteRef(workspace, ref, head) {
182
+ return await db.transaction(async (tx) => {
183
+ if (!await lock(tx, workspace)) return false;
184
+ const [current] = await tx.select({ head: refs$2.head }).from(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref)));
185
+ if (!current || current.head !== head) return false;
186
+ await tx.update(objects$2).set({ size: -1 }).where(and(eq(objects$2.workspace, workspace), gte(objects$2.size, 0), sql`${digestOf} in ${manifestDigests(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref)))}`, sql`${digestOf} not in ${manifestDigests(and(eq(revisions$2.workspace, workspace), ne(revisions$2.ref, ref), eq(revisions$2.committed, true)))}`));
187
+ await tx.delete(revisions$2).where(and(eq(revisions$2.workspace, workspace), eq(revisions$2.ref, ref)));
188
+ await tx.delete(refs$2).where(and(eq(refs$2.workspace, workspace), eq(refs$2.ref, ref)));
189
+ return true;
190
+ });
191
+ },
192
+ async markedObjects(workspace) {
193
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(and(eq(objects$2.workspace, workspace), lt(objects$2.size, 0)))).map((row) => row.key);
194
+ },
195
+ async dropMarkedObjects(workspace, keys) {
196
+ if (!keys.length) return;
197
+ await db.delete(objects$2).where(and(eq(objects$2.workspace, workspace), sql`${objects$2.digest} in ${textValues(keys)}`, lt(objects$2.size, 0)));
198
+ },
199
+ async tombstone(workspace) {
200
+ await db.transaction(async (tx) => {
201
+ await tx.update(workspaces$2).set({ deleted: true }).where(eq(workspaces$2.workspace, workspace));
202
+ await tx.delete(refs$2).where(eq(refs$2.workspace, workspace));
203
+ });
204
+ },
205
+ async objects(workspace) {
206
+ return (await db.select({ key: objects$2.digest }).from(objects$2).where(eq(objects$2.workspace, workspace))).map((row) => row.key);
207
+ },
208
+ async purge(workspace) {
209
+ await db.transaction(async (tx) => {
210
+ await tx.delete(revisions$2).where(eq(revisions$2.workspace, workspace));
211
+ await tx.delete(objects$2).where(eq(objects$2.workspace, workspace));
212
+ await tx.delete(metadata$2).where(eq(metadata$2.workspace, workspace));
213
+ });
214
+ },
215
+ async getMeta(workspace, key) {
216
+ const [row] = await db.select({ value: metadata$2.value }).from(metadata$2).where(and(eq(metadata$2.workspace, workspace), eq(metadata$2.key, key), active$1(workspace)));
217
+ return row?.value;
218
+ },
219
+ async setMeta(workspace, key, value) {
220
+ await db.transaction(async (tx) => {
221
+ if (!await lock(tx, workspace)) return;
222
+ await tx.insert(metadata$2).values({
223
+ workspace,
224
+ key,
225
+ value: value === null ? sql`'null'::json` : value
226
+ }).onConflictDoUpdate({
227
+ target: [metadata$2.workspace, metadata$2.key],
228
+ set: { value: sql`excluded.value` }
229
+ });
230
+ });
231
+ },
232
+ async deleteMeta(workspace, key) {
233
+ await db.delete(metadata$2).where(and(eq(metadata$2.workspace, workspace), eq(metadata$2.key, key)));
234
+ }
235
+ };
236
+ }
10
237
  /** Include these tables in a Database Definition and apply its migrations. */
11
238
  const workspaceHistorySchema = {
12
239
  workspaceHistoryWorkspaces: sqliteTable("workspace_history_workspaces", {
13
- workspace: text("workspace").primaryKey(),
14
- deleted: integer("deleted", { mode: "boolean" }).notNull().default(false)
240
+ workspace: text$1("workspace").primaryKey(),
241
+ deleted: integer$1("deleted", { mode: "boolean" }).notNull().default(false)
15
242
  }),
16
243
  workspaceHistoryRefs: sqliteTable("workspace_history_refs", {
17
- workspace: text("workspace").notNull(),
18
- ref: text("ref").notNull(),
19
- head: text("head"),
20
- sequence: integer("sequence").notNull().default(0)
21
- }, (table) => [primaryKey({ columns: [table.workspace, table.ref] })]),
244
+ workspace: text$1("workspace").notNull(),
245
+ ref: text$1("ref").notNull(),
246
+ head: text$1("head"),
247
+ sequence: integer$1("sequence").notNull().default(0)
248
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.ref] })]),
22
249
  workspaceHistoryRevisions: sqliteTable("workspace_history_revisions", {
23
- workspace: text("workspace").notNull(),
24
- id: text("id").notNull(),
25
- ref: text("ref").notNull(),
26
- parentId: text("parent_id"),
27
- sequence: integer("sequence").notNull(),
28
- createdAt: text("created_at").notNull(),
29
- message: text("message"),
30
- metadata: text("metadata", { mode: "json" }).$type(),
31
- files: integer("files").notNull(),
32
- bytes: integer("bytes").notNull(),
33
- entries: text("entries", { mode: "json" }).$type().notNull(),
34
- committed: integer("committed", { mode: "boolean" }).notNull().default(false)
35
- }, (table) => [primaryKey({ columns: [table.workspace, table.id] }), index("workspace_history_timeline").on(table.workspace, table.ref, table.committed, table.sequence)]),
250
+ workspace: text$1("workspace").notNull(),
251
+ id: text$1("id").notNull(),
252
+ ref: text$1("ref").notNull(),
253
+ parentId: text$1("parent_id"),
254
+ sequence: integer$1("sequence").notNull(),
255
+ createdAt: text$1("created_at").notNull(),
256
+ message: text$1("message"),
257
+ metadata: text$1("metadata", { mode: "json" }).$type(),
258
+ files: integer$1("files").notNull(),
259
+ bytes: integer$1("bytes").notNull(),
260
+ entries: text$1("entries", { mode: "json" }).$type().notNull(),
261
+ committed: integer$1("committed", { mode: "boolean" }).notNull().default(false)
262
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.id] }), index$1("workspace_history_timeline").on(table.workspace, table.ref, table.committed, table.sequence)]),
36
263
  workspaceHistoryObjects: sqliteTable("workspace_history_objects", {
37
- workspace: text("workspace").notNull(),
38
- digest: text("digest").notNull(),
39
- size: integer("size").notNull()
40
- }, (table) => [primaryKey({ columns: [table.workspace, table.digest] })]),
264
+ workspace: text$1("workspace").notNull(),
265
+ digest: text$1("digest").notNull(),
266
+ size: integer$1("size").notNull()
267
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.digest] })]),
41
268
  workspaceHistoryMetadata: sqliteTable("workspace_history_metadata", {
42
- workspace: text("workspace").notNull(),
43
- key: text("key").notNull(),
44
- value: text("value", { mode: "json" }).$type().notNull()
45
- }, (table) => [primaryKey({ columns: [table.workspace, table.key] })])
269
+ workspace: text$1("workspace").notNull(),
270
+ key: text$1("key").notNull(),
271
+ value: text$1("value", { mode: "json" }).$type().notNull()
272
+ }, (table) => [primaryKey$1({ columns: [table.workspace, table.key] })])
46
273
  };
47
274
  //#endregion
48
- //#region src/storage/blob-database.ts
275
+ //#region src/storage/history-index-sqlite.ts
49
276
  const { workspaceHistoryWorkspaces: workspaces, workspaceHistoryRefs: refs, workspaceHistoryRevisions: revisions, workspaceHistoryObjects: objects, workspaceHistoryMetadata: metadata } = workspaceHistorySchema;
277
+ function activeObject(workspace, digest) {
278
+ return sql`${objects.workspace} = ${workspace} and ${objects.size} >= 0
279
+ and ${objects.digest} >= ${digest} and ${objects.digest} < ${digest} || '.'`;
280
+ }
281
+ function active(workspace) {
282
+ return sql`exists (select 1 from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0)`;
283
+ }
284
+ /** Each write is one atomic batch. */
285
+ function sqliteHistoryIndex(db) {
286
+ const ref = async (workspace, name) => {
287
+ const [row] = await db.select().from(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, name), active(workspace)));
288
+ return row;
289
+ };
290
+ return {
291
+ async claim(current, legacy) {
292
+ const [currentRows, legacyRows] = await db.batch([
293
+ db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, current)),
294
+ db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, legacy ?? current)),
295
+ db.insert(workspaces).select(sql`
296
+ select ${current}, 0
297
+ where not exists (
298
+ select 1 from ${workspaces} where ${workspaces.workspace} = ${legacy ?? current}
299
+ )
300
+ `).onConflictDoNothing()
301
+ ]);
302
+ return currentRows[0]?.workspace ?? legacyRows[0]?.workspace ?? current;
303
+ },
304
+ async deleted(workspace) {
305
+ const [row] = await db.select({ deleted: workspaces.deleted }).from(workspaces).where(eq(workspaces.workspace, workspace));
306
+ return row?.deleted;
307
+ },
308
+ ref,
309
+ async heads(workspace) {
310
+ const heads = await db.select({
311
+ ref: refs.ref,
312
+ head: refs.head
313
+ }).from(refs).where(and(eq(refs.workspace, workspace), isNotNull(refs.head), active(workspace)));
314
+ if (!heads.length) return [];
315
+ const rows = await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.committed, true), inArray(revisions.id, heads.map((row) => row.head)), active(workspace)));
316
+ const byId = new Map(rows.map((row) => [row.id, row]));
317
+ return heads.flatMap(({ ref, head }) => {
318
+ const revision = byId.get(head);
319
+ return revision ? [{
320
+ ref,
321
+ revision
322
+ }] : [];
323
+ });
324
+ },
325
+ async revision(workspace, id) {
326
+ const [row] = await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), eq(revisions.committed, true), active(workspace)));
327
+ return row;
328
+ },
329
+ async list(workspace, { ref, before, path, limit }) {
330
+ const previousEntries = sql`
331
+ coalesce((
332
+ select previous.entries
333
+ from ${revisions} as previous
334
+ where previous.workspace = ${revisions.workspace}
335
+ and previous.id = ${revisions.parentId}
336
+ and previous.committed = 1
337
+ ), '{}')
338
+ `;
339
+ const pathFilter = path === void 0 ? void 0 : sql`(
340
+ exists (
341
+ select 1
342
+ from json_each(${revisions.entries}) as current_file
343
+ left join json_each(${previousEntries}) as previous_file
344
+ on previous_file.key = current_file.key
345
+ where (current_file.key = ${path} or substr(current_file.key, 1, length(${path}) + 1) = ${path} || '/')
346
+ and (
347
+ previous_file.key is null
348
+ or json_extract(current_file.value, '$.digest') is not json_extract(previous_file.value, '$.digest')
349
+ or json_extract(current_file.value, '$.size') is not json_extract(previous_file.value, '$.size')
350
+ or json_extract(current_file.value, '$.mediaType') is not json_extract(previous_file.value, '$.mediaType')
351
+ or json_extract(current_file.value, '$.metadata') is not json_extract(previous_file.value, '$.metadata')
352
+ )
353
+ )
354
+ or exists (
355
+ select 1
356
+ from json_each(${previousEntries}) as previous_file
357
+ left join json_each(${revisions.entries}) as current_file
358
+ on current_file.key = previous_file.key
359
+ where (previous_file.key = ${path} or substr(previous_file.key, 1, length(${path}) + 1) = ${path} || '/')
360
+ and current_file.key is null
361
+ )
362
+ )`;
363
+ return await db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), eq(revisions.committed, true), before === void 0 ? void 0 : lt(revisions.sequence, before), pathFilter, active(workspace))).orderBy(desc(revisions.sequence)).limit(limit);
364
+ },
365
+ async usage(workspace) {
366
+ const [result] = await db.values(sql`
367
+ select coalesce(sum(size), 0) as bytes, count(*) as objects from (
368
+ select distinct json_extract(file.value, '$.digest') as digest,
369
+ json_extract(file.value, '$.size') as size
370
+ from ${revisions}, json_each(${revisions.entries}) as file
371
+ where ${revisions.workspace} = ${workspace} and ${revisions.committed} = 1
372
+ and ${active(workspace)}
373
+ )
374
+ `);
375
+ return {
376
+ bytes: result?.[0] ?? 0,
377
+ objects: result?.[1] ?? 0
378
+ };
379
+ },
380
+ async objectKey(workspace, digest) {
381
+ const [object] = await db.select({ key: objects.digest }).from(objects).where(activeObject(workspace, digest)).limit(1);
382
+ return object?.key;
383
+ },
384
+ async register(workspace, registry) {
385
+ await db.insert(objects).select(sql`
386
+ select ${workspaces.workspace}, json_extract(object.value, '$.key'), json_extract(object.value, '$.size')
387
+ from ${workspaces}, json_each(${JSON.stringify(registry)}) as object
388
+ where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
389
+ and not exists (select 1 from ${objects} where ${activeObject(workspace, sql`json_extract(object.value, '$.digest')`)})
390
+ `).onConflictDoNothing();
391
+ },
392
+ async objectKeys(workspace, digests) {
393
+ return await db.values(sql`
394
+ select needed.value, ${objects.digest}
395
+ from json_each(${JSON.stringify(digests)}) as needed join ${objects} on ${activeObject(workspace, sql`needed.value`)}
396
+ `);
397
+ },
398
+ async hasObject(workspace, key) {
399
+ const [row] = await db.select({ key: objects.digest }).from(objects).where(and(eq(objects.workspace, workspace), eq(objects.digest, key), sql`${objects.size} >= 0`)).limit(1);
400
+ return row !== void 0;
401
+ },
402
+ async publish(workspace, { revision: row, ifHead, ifHeads, keys, complete }) {
403
+ const objectsReady = sql`${complete} and not exists (
404
+ select 1 from json_each(${JSON.stringify(keys)}) as verified
405
+ where not exists (
406
+ select 1 from ${objects}
407
+ where ${objects.workspace} = ${workspace} and ${objects.digest} = verified.value and ${objects.size} >= 0
408
+ )
409
+ )`;
410
+ const [, , changed] = await db.batch([
411
+ db.insert(refs).select(sql`
412
+ select ${workspaces.workspace}, ${row.ref}, null, 0
413
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0 and ${objectsReady}
414
+ `).onConflictDoNothing(),
415
+ db.insert(revisions).select(sql`
416
+ select ${row.workspace}, ${row.id}, ${row.ref}, ${row.parentId}, ${row.sequence}, ${row.createdAt},
417
+ ${row.message}, ${row.metadata === null ? null : JSON.stringify(row.metadata)},
418
+ ${row.files}, ${row.bytes}, ${JSON.stringify(row.entries)}, 0
419
+ from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0 and ${objectsReady}
420
+ `).onConflictDoNothing(),
421
+ db.update(refs).set({
422
+ head: row.id,
423
+ sequence: sql`${refs.sequence} + 1`
424
+ }).where(and(eq(refs.workspace, workspace), eq(refs.ref, row.ref), sql`${refs.head} is ${ifHead}`, ...ifHeads.map(([expectedRef, expectedHead]) => expectedHead === null ? sql`(not exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef}) or exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is null))` : sql`exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is ${expectedHead})`), objectsReady, active(workspace))).returning({ head: refs.head }),
425
+ db.update(revisions).set({ committed: true }).where(and(eq(revisions.workspace, workspace), eq(revisions.id, row.id), sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${row.ref} and ${refs.head} = ${row.id})`, active(workspace)))
426
+ ]);
427
+ return changed.length > 0;
428
+ },
429
+ async deleteRef(workspace, ref, head) {
430
+ const sameHead = sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${ref} and ${refs.head} is ${head})`;
431
+ const [, , removed] = await db.batch([
432
+ db.update(objects).set({ size: -1 }).where(and(eq(objects.workspace, workspace), sql`${objects.size} >= 0`, sameHead, sql`substr(${objects.digest}, 1, 64) in (
433
+ select json_extract(file.value, '$.digest')
434
+ from ${revisions}, json_each(${revisions.entries}) as file
435
+ where ${revisions.workspace} = ${workspace} and ${revisions.ref} = ${ref}
436
+ )`, sql`substr(${objects.digest}, 1, 64) not in (
437
+ select json_extract(file.value, '$.digest')
438
+ from ${revisions}, json_each(${revisions.entries}) as file
439
+ where ${revisions.workspace} = ${workspace} and ${revisions.ref} <> ${ref} and ${revisions.committed} = 1
440
+ )`)),
441
+ db.delete(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), sameHead)),
442
+ db.delete(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), sql`${refs.head} is ${head}`)).returning({ ref: refs.ref })
443
+ ]);
444
+ return removed.length > 0;
445
+ },
446
+ async markedObjects(workspace) {
447
+ return (await db.select({ key: objects.digest }).from(objects).where(and(eq(objects.workspace, workspace), sql`${objects.size} < 0`))).map((row) => row.key);
448
+ },
449
+ async dropMarkedObjects(workspace, keys) {
450
+ await db.delete(objects).where(and(eq(objects.workspace, workspace), inArray(objects.digest, keys), sql`${objects.size} < 0`));
451
+ },
452
+ async tombstone(workspace) {
453
+ await db.batch([db.update(workspaces).set({ deleted: true }).where(eq(workspaces.workspace, workspace)), db.delete(refs).where(eq(refs.workspace, workspace))]);
454
+ },
455
+ async objects(workspace) {
456
+ return (await db.select({ key: objects.digest }).from(objects).where(eq(objects.workspace, workspace))).map((row) => row.key);
457
+ },
458
+ async purge(workspace) {
459
+ await db.batch([
460
+ db.delete(revisions).where(eq(revisions.workspace, workspace)),
461
+ db.delete(objects).where(eq(objects.workspace, workspace)),
462
+ db.delete(metadata).where(eq(metadata.workspace, workspace))
463
+ ]);
464
+ },
465
+ async getMeta(workspace, key) {
466
+ const [row] = await db.select().from(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key), active(workspace)));
467
+ return row?.value;
468
+ },
469
+ async setMeta(workspace, key, value) {
470
+ await db.insert(metadata).select(db.select({
471
+ workspace: sql`${workspace}`.as("workspace"),
472
+ key: sql`${key}`.as("key"),
473
+ value: sql`${JSON.stringify(value)}`.as("value")
474
+ }).from(workspaces).where(and(eq(workspaces.workspace, workspace), eq(workspaces.deleted, false)))).onConflictDoUpdate({
475
+ target: [metadata.workspace, metadata.key],
476
+ set: { value: sql`${JSON.stringify(value)}` }
477
+ });
478
+ },
479
+ async deleteMeta(workspace, key) {
480
+ await db.delete(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key)));
481
+ }
482
+ };
483
+ }
484
+ //#endregion
485
+ //#region src/storage/blob-database.ts
50
486
  function publicRevision(row) {
51
487
  const revision = {
52
488
  id: row.id,
@@ -68,7 +504,7 @@ var ContentAddressedWorkspaceStore = class {
68
504
  #dirty = false;
69
505
  #baseline;
70
506
  #queue = Promise.resolve();
71
- #database;
507
+ #backend;
72
508
  constructor(options) {
73
509
  this.options = options;
74
510
  if (typeof options.workspace !== "string" || !options.workspace) throw workspaceError("[vitehub] Blob + Database Store requires a workspace identity.");
@@ -81,42 +517,63 @@ var ContentAddressedWorkspaceStore = class {
81
517
  const legacy = `${legacyPrefix}/${digest}`;
82
518
  return legacy === current ? [current] : [current, legacy];
83
519
  });
520
+ provideWorkspaceStoreTarget(this, () => this.#storeTarget());
84
521
  }
85
- [workspaceStoreTarget]() {
522
+ async #storeTarget() {
523
+ return (await this.#backendReady()).target;
524
+ }
525
+ [blobDatabaseSources]() {
526
+ const { blob, database } = this.options;
86
527
  return {
87
- provider: "blob-database",
88
- workspace: this.options.workspace,
89
- database: this.#db
528
+ blob: typeof blob === "string" ? blob : void 0,
529
+ database: typeof database === "string" ? database : void 0
530
+ };
531
+ }
532
+ #backendReady() {
533
+ this.#backend ??= this.#connect().catch((error) => {
534
+ this.#backend = void 0;
535
+ throw error;
536
+ });
537
+ return this.#backend;
538
+ }
539
+ async #connect() {
540
+ const { blob, database, workspace } = this.options;
541
+ const storage = typeof blob === "string" ? await useBlobStore(blob) : blob;
542
+ const db = typeof database === "string" ? (await useNamedDatabase())(database).db : typeof database === "function" ? database() : database;
543
+ if (is(db, PgAsyncDatabase)) return {
544
+ blob: storage,
545
+ index: postgresHistoryIndex(db),
546
+ target: {
547
+ provider: "blob-database",
548
+ workspace,
549
+ dialect: "postgresql",
550
+ database: db
551
+ }
552
+ };
553
+ if (isSqliteDatabase(db)) return {
554
+ blob: storage,
555
+ index: sqliteHistoryIndex(db),
556
+ target: {
557
+ provider: "blob-database",
558
+ workspace,
559
+ dialect: "sqlite",
560
+ database: db
561
+ }
90
562
  };
563
+ throw workspaceErrorDiagnostics.WORKSPACE_R0077({ message: `[vitehub] The \`database\` of the Blob + Database Store for workspace "${workspace}" is not a Drizzle database.` });
91
564
  }
92
- get #db() {
93
- if (this.#database) return this.#database;
94
- const { database } = this.options;
95
- const resolved = typeof database === "function" ? database() : database;
96
- if (typeof resolved?.batch !== "function") throw workspaceErrorDiagnostics.WORKSPACE_R0077({ message: `[vitehub] The \`database\` of the Blob + Database Store for workspace "${this.options.workspace}" is not a Drizzle database.` });
97
- return this.#database = resolved;
565
+ async #index() {
566
+ return (await this.#backendReady()).index;
567
+ }
568
+ async #blob() {
569
+ return (await this.#backendReady()).blob;
98
570
  }
99
571
  history = {
100
572
  head: async (options) => await this.#head(normalizeHistoryRef(options?.ref)),
101
573
  list: async (options) => await this.#listHistory(options),
102
574
  refs: async () => await this.#refs(),
103
575
  open: async (id) => await this.#open(id),
104
- usage: async () => {
105
- const workspace = await this.#key();
106
- const [result] = await this.#db.values(sql`
107
- select coalesce(sum(size), 0) as bytes, count(*) as objects from (
108
- select distinct json_extract(file.value, '$.digest') as digest,
109
- json_extract(file.value, '$.size') as size
110
- from ${revisions}, json_each(${revisions.entries}) as file
111
- where ${revisions.workspace} = ${workspace} and ${revisions.committed} = 1
112
- and ${this.#active(workspace)}
113
- )
114
- `);
115
- return {
116
- bytes: result?.[0] ?? 0,
117
- objects: result?.[1] ?? 0
118
- };
119
- },
576
+ usage: async () => await (await this.#index()).usage(await this.#key()),
120
577
  commit: async (options) => await this.#mutate(async () => {
121
578
  const revision = await this.#commit(options);
122
579
  if (revision.ref === "main") {
@@ -125,40 +582,24 @@ var ContentAddressedWorkspaceStore = class {
125
582
  this.#baseline = void 0;
126
583
  }
127
584
  return revision;
128
- })
585
+ }),
586
+ deleteRef: async (options) => await this.#mutate(async () => await this.#deleteRef(readHistoryDeleteRef(options)))
129
587
  };
130
588
  async #key() {
131
- const candidates = await this.#namespace;
132
- this.#ready ??= this.#db.batch([
133
- this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[0])),
134
- this.#db.select({ workspace: workspaces.workspace }).from(workspaces).where(eq(workspaces.workspace, candidates[1] ?? candidates[0])),
135
- this.#db.insert(workspaces).select(sql`
136
- select ${candidates[0]}, 0
137
- where not exists (
138
- select 1 from ${workspaces} where ${workspaces.workspace} = ${candidates[1] ?? candidates[0]}
139
- )
140
- `).onConflictDoNothing()
141
- ]).then((results) => {
142
- const [current, legacy] = results;
143
- return current[0]?.workspace ?? legacy[0]?.workspace ?? candidates[0];
144
- }).catch((error) => {
589
+ this.#ready ??= Promise.all([this.#namespace, this.#index()]).then(([candidates, index]) => index.claim(candidates[0], candidates[1])).catch((error) => {
145
590
  this.#ready = void 0;
146
591
  throw error;
147
592
  });
148
593
  return await this.#ready;
149
594
  }
150
- #active(workspace) {
151
- return sql`exists (select 1 from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0)`;
152
- }
153
595
  async #isDeleted() {
154
596
  const workspace = await this.#key();
155
- const [row] = await this.#db.select({ deleted: workspaces.deleted }).from(workspaces).where(eq(workspaces.workspace, workspace));
156
- if (!row) throw workspaceError("[vitehub] Workspace history identity is missing.");
157
- return row.deleted;
597
+ const deleted = await (await this.#index()).deleted(workspace);
598
+ if (deleted === void 0) throw workspaceError("[vitehub] Workspace history identity is missing.");
599
+ return deleted;
158
600
  }
159
601
  async #ref(workspace, ref) {
160
- const [row] = await this.#db.select().from(refs).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), this.#active(workspace)));
161
- return row;
602
+ return await (await this.#index()).ref(workspace, ref);
162
603
  }
163
604
  async #head(ref) {
164
605
  const workspace = await this.#key();
@@ -167,20 +608,10 @@ var ContentAddressedWorkspaceStore = class {
167
608
  }
168
609
  async #refs() {
169
610
  const workspace = await this.#key();
170
- const heads = await this.#db.select({
171
- ref: refs.ref,
172
- head: refs.head
173
- }).from(refs).where(and(eq(refs.workspace, workspace), isNotNull(refs.head), this.#active(workspace)));
174
- if (!heads.length) return [];
175
- const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.committed, true), inArray(revisions.id, heads.map((row) => row.head)), this.#active(workspace)));
176
- const byId = new Map(rows.map((row) => [row.id, row]));
177
- return heads.flatMap(({ ref, head }) => {
178
- const row = byId.get(head);
179
- return row ? [{
180
- name: ref,
181
- head: publicRevision(row)
182
- }] : [];
183
- }).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
611
+ return (await (await this.#index()).heads(workspace)).map(({ ref, revision }) => ({
612
+ name: ref,
613
+ head: publicRevision(revision)
614
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
184
615
  }
185
616
  #deleted() {
186
617
  throw new ViteHubError("WORKSPACE_NOT_FOUND", "[vitehub] This Workspace has been deleted. Use a new workspace identity.", { details: { workspace: this.options.workspace } });
@@ -190,7 +621,7 @@ var ContentAddressedWorkspaceStore = class {
190
621
  }
191
622
  async #revision(id) {
192
623
  const workspace = await this.#key();
193
- const [row] = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), eq(revisions.committed, true), this.#active(workspace)));
624
+ const row = await (await this.#index()).revision(workspace, id);
194
625
  if (!row) throw new ViteHubError("WORKSPACE_NOT_FOUND", `[vitehub] Workspace revision does not exist: ${id}.`);
195
626
  return row;
196
627
  }
@@ -202,40 +633,12 @@ var ContentAddressedWorkspaceStore = class {
202
633
  const workspace = await this.#key();
203
634
  const cursor = options.cursor ? await this.#revision(options.cursor) : void 0;
204
635
  if (cursor && cursor.ref !== ref) throw workspaceErrorDiagnostics.WORKSPACE_R0070({ message: `[vitehub] History cursor belongs to ref "${cursor.ref}". Pass it with the ref that returned it.` });
205
- const previousEntries = sql`
206
- coalesce((
207
- select previous.entries
208
- from ${revisions} as previous
209
- where previous.workspace = ${revisions.workspace}
210
- and previous.id = ${revisions.parentId}
211
- and previous.committed = 1
212
- ), '{}')
213
- `;
214
- const pathFilter = path === void 0 ? void 0 : sql`(
215
- exists (
216
- select 1
217
- from json_each(${revisions.entries}) as current_file
218
- left join json_each(${previousEntries}) as previous_file
219
- on previous_file.key = current_file.key
220
- where (current_file.key = ${path} or substr(current_file.key, 1, length(${path}) + 1) = ${path} || '/')
221
- and (
222
- previous_file.key is null
223
- or json_extract(current_file.value, '$.digest') is not json_extract(previous_file.value, '$.digest')
224
- or json_extract(current_file.value, '$.size') is not json_extract(previous_file.value, '$.size')
225
- or json_extract(current_file.value, '$.mediaType') is not json_extract(previous_file.value, '$.mediaType')
226
- or json_extract(current_file.value, '$.metadata') is not json_extract(previous_file.value, '$.metadata')
227
- )
228
- )
229
- or exists (
230
- select 1
231
- from json_each(${previousEntries}) as previous_file
232
- left join json_each(${revisions.entries}) as current_file
233
- on current_file.key = previous_file.key
234
- where (previous_file.key = ${path} or substr(previous_file.key, 1, length(${path}) + 1) = ${path} || '/')
235
- and current_file.key is null
236
- )
237
- )`;
238
- const rows = await this.#db.select().from(revisions).where(and(eq(revisions.workspace, workspace), eq(revisions.ref, ref), eq(revisions.committed, true), cursor ? lt(revisions.sequence, cursor.sequence) : void 0, pathFilter, this.#active(workspace))).orderBy(desc(revisions.sequence)).limit(limit + 1);
636
+ const rows = await (await this.#index()).list(workspace, {
637
+ ref,
638
+ before: cursor?.sequence,
639
+ path,
640
+ limit: limit + 1
641
+ });
239
642
  const result = { revisions: rows.slice(0, limit).map(publicRevision) };
240
643
  if (rows.length > limit) result.cursor = rows[limit - 1].id;
241
644
  return result;
@@ -286,7 +689,9 @@ var ContentAddressedWorkspaceStore = class {
286
689
  const normalized = normalizeHistoryPath(path);
287
690
  const file = Object.hasOwn(row.entries, normalized) ? row.entries[normalized] : void 0;
288
691
  if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
289
- const [error, body] = await this.options.blob.get(`${workspace}/sha256/${file.digest}`);
692
+ const key = await (await this.#index()).objectKey(workspace, file.digest);
693
+ if (!key) throw workspaceError(`[vitehub] Retained history object is missing: ${file.digest}.`);
694
+ const [error, body] = await (await this.#blob()).get(`${workspace}/sha256/${key}`);
290
695
  if (error) throw error;
291
696
  if (!body) throw workspaceError(`[vitehub] Retained history object is missing: ${file.digest}.`);
292
697
  const bytes = new Uint8Array(await body.arrayBuffer());
@@ -304,6 +709,8 @@ var ContentAddressedWorkspaceStore = class {
304
709
  return [normalizeHistoryRef(name), head];
305
710
  });
306
711
  const workspace = await this.#key();
712
+ const index = await this.#index();
713
+ const blob = await this.#blob();
307
714
  await this.#assertActive();
308
715
  const current = await this.#ref(workspace, ref);
309
716
  if ((current?.head ?? null) !== options.ifHead) rejectHistoryHead(options, this.#conflict(ref, options.ifHead, current?.head ?? null));
@@ -349,40 +756,41 @@ var ContentAddressedWorkspaceStore = class {
349
756
  entries: sorted
350
757
  };
351
758
  const id = await sha256(manifest);
352
- const registry = [...contents].map(([digest, bytes]) => ({
353
- digest,
354
- size: bytes.byteLength
355
- }));
356
- await this.#db.insert(objects).select(sql`
357
- select ${workspaces.workspace}, json_extract(object.value, '$.digest'), json_extract(object.value, '$.size')
358
- from ${workspaces}, json_each(${JSON.stringify(registry)}) as object
359
- where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
360
- `).onConflictDoNothing();
361
- await this.#assertActive();
362
- const upload = async ([digest, bytes]) => {
363
- const key = `${workspace}/sha256/${digest}`;
364
- const [headError, object] = await this.options.blob.head(key);
759
+ const register = async () => {
760
+ await index.register(workspace, [...contents].map(([digest, bytes]) => ({
761
+ digest,
762
+ key: `${digest}-${crypto.randomUUID()}`,
763
+ size: bytes.byteLength
764
+ })));
765
+ await this.#assertActive();
766
+ return await index.objectKeys(workspace, [...contents.keys()]);
767
+ };
768
+ const upload = async ([digest, generation]) => {
769
+ const key = `${workspace}/sha256/${generation}`;
770
+ const [headError, object] = await blob.head(key);
365
771
  if (headError && headError.code !== "BLOB_NOT_FOUND") throw headError;
366
772
  if (!object) {
367
- const [uploadError] = await this.options.blob.put(key, bytes, {
773
+ const [uploadError] = await blob.put(key, contents.get(digest), {
368
774
  addRandomSuffix: false,
369
775
  contentType: "application/octet-stream"
370
776
  });
777
+ if (!await index.hasObject(workspace, generation) || await this.#isDeleted()) {
778
+ await this.#removeObject(key);
779
+ await this.#assertActive();
780
+ return;
781
+ }
371
782
  if (uploadError) {
372
- const [concurrentError, concurrentObject] = await this.options.blob.head(key);
783
+ const [concurrentError, concurrentObject] = await blob.head(key);
373
784
  if (concurrentError || !concurrentObject) throw uploadError;
374
785
  }
375
786
  }
376
- if (await this.#isDeleted()) {
377
- await this.#removeObject(key);
378
- this.#deleted();
787
+ };
788
+ const uploadAll = async (uploads) => {
789
+ for (let offset = 0; offset < uploads.length; offset += 8) {
790
+ const results = await Promise.allSettled(uploads.slice(offset, offset + 8).map(upload));
791
+ for (const result of results) if (result.status === "rejected") throw result.reason;
379
792
  }
380
793
  };
381
- const uploads = [...contents];
382
- for (let offset = 0; offset < uploads.length; offset += 8) {
383
- const results = await Promise.allSettled(uploads.slice(offset, offset + 8).map(upload));
384
- for (const result of results) if (result.status === "rejected") throw result.reason;
385
- }
386
794
  const row = {
387
795
  ...manifest,
388
796
  entries: { ...sorted },
@@ -392,46 +800,70 @@ var ContentAddressedWorkspaceStore = class {
392
800
  files: Object.keys(sorted).length,
393
801
  bytes: Object.values(sorted).reduce((total, entry) => total + entry.size, 0)
394
802
  };
395
- expectedHeads.map(([name, head]) => sql`(select expected.head from ${refs} as expected where expected.workspace = ${workspace} and expected.ref = ${name}) is ${head}`);
396
- const [, , changed] = await this.#db.batch([
397
- this.#db.insert(refs).select(sql`
398
- select ${workspaces.workspace}, ${ref}, null, 0
399
- from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
400
- `).onConflictDoNothing(),
401
- this.#db.insert(revisions).select(sql`
402
- select ${row.workspace}, ${row.id}, ${row.ref}, ${row.parentId}, ${row.sequence}, ${row.createdAt},
403
- ${row.message}, ${row.metadata === null ? null : JSON.stringify(row.metadata)},
404
- ${row.files}, ${row.bytes}, ${JSON.stringify(row.entries)}, 0
405
- from ${workspaces} where ${workspaces.workspace} = ${workspace} and ${workspaces.deleted} = 0
406
- `).onConflictDoNothing(),
407
- this.#db.update(refs).set({
408
- head: id,
409
- sequence: sql`${refs.sequence} + 1`
410
- }).where(and(eq(refs.workspace, workspace), eq(refs.ref, ref), sql`${refs.head} is ${options.ifHead}`, ...Object.entries(options.ifHeads ?? {}).map(([expectedRef, expectedHead]) => expectedHead === null ? sql`(not exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef}) or exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is null))` : sql`exists (select 1 from ${refs} as cross_ref where cross_ref.workspace = ${workspace} and cross_ref.ref = ${expectedRef} and cross_ref.head is ${expectedHead})`), this.#active(workspace))).returning({ head: refs.head }),
411
- this.#db.update(revisions).set({ committed: true }).where(and(eq(revisions.workspace, workspace), eq(revisions.id, id), sql`exists (select 1 from ${refs} where ${refs.workspace} = ${workspace} and ${refs.ref} = ${ref} and ${refs.head} = ${id})`, this.#active(workspace)))
412
- ]);
413
- if (!changed.length) {
803
+ for (let attempt = 0;; attempt++) {
804
+ const uploads = await register();
805
+ await uploadAll(uploads);
806
+ if (await index.publish(workspace, {
807
+ revision: {
808
+ ...row,
809
+ committed: false
810
+ },
811
+ ifHead: options.ifHead,
812
+ ifHeads: expectedHeads,
813
+ keys: uploads.map(([, key]) => key),
814
+ complete: uploads.length === contents.size
815
+ })) break;
414
816
  if (await this.#isDeleted()) this.#deleted();
415
817
  for (const [name, expected] of expectedHeads) {
416
818
  const actual = (await this.#ref(workspace, name))?.head ?? null;
417
819
  if (actual !== expected) throw this.#conflict(name, expected, actual);
418
820
  }
419
- rejectHistoryHead(options, this.#conflict(ref, options.ifHead, (await this.#ref(workspace, ref))?.head ?? null));
821
+ const actual = (await this.#ref(workspace, ref))?.head ?? null;
822
+ if (actual !== options.ifHead) rejectHistoryHead(options, this.#conflict(ref, options.ifHead, actual));
823
+ if (attempt === 4) throw workspaceConflict("[vitehub] History objects of this commit are being deleted by history.deleteRef(). Retry the commit.", { details: {
824
+ workspace: this.options.workspace,
825
+ ref
826
+ } });
827
+ await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** attempt));
420
828
  }
421
829
  return publicRevision({
422
830
  ...row,
423
831
  committed: true
424
832
  });
425
833
  }
834
+ async #deleteRef({ ref, ifHead }) {
835
+ const workspace = await this.#key();
836
+ await this.#assertActive();
837
+ const current = await this.#ref(workspace, ref);
838
+ const head = current?.head ?? null;
839
+ if (ifHead !== void 0 && head !== ifHead) throw this.#conflict(ref, ifHead, head);
840
+ if (!current) {
841
+ await this.#removeUnusedObjects(workspace);
842
+ return false;
843
+ }
844
+ if (!await (await this.#index()).deleteRef(workspace, ref, head)) throw this.#conflict(ref, head, (await this.#ref(workspace, ref))?.head ?? null);
845
+ await this.#removeUnusedObjects(workspace);
846
+ return true;
847
+ }
848
+ async #removeUnusedObjects(workspace) {
849
+ const index = await this.#index();
850
+ const marked = await index.markedObjects(workspace);
851
+ for (let offset = 0; offset < marked.length; offset += 8) {
852
+ const batch = marked.slice(offset, offset + 8);
853
+ await Promise.all(batch.map((key) => this.#removeObject(`${workspace}/sha256/${key}`)));
854
+ await index.dropMarkedObjects(workspace, batch);
855
+ }
856
+ }
426
857
  #conflict(ref, expected, actual) {
427
858
  return historyConflict(ref, expected, actual, { workspace: this.options.workspace });
428
859
  }
429
860
  async #removeObject(key) {
430
- const [headError, object] = await this.options.blob.head(key);
861
+ const blob = await this.#blob();
862
+ const [headError, object] = await blob.head(key);
431
863
  if (headError?.code === "BLOB_NOT_FOUND") return;
432
864
  if (headError) throw headError;
433
865
  if (!object) return;
434
- const [error] = await this.options.blob.delete(key);
866
+ const [error] = await blob.delete(key);
435
867
  if (error && error.code !== "BLOB_NOT_FOUND") throw error;
436
868
  }
437
869
  async delete() {
@@ -439,14 +871,15 @@ var ContentAddressedWorkspaceStore = class {
439
871
  }
440
872
  async #delete() {
441
873
  const workspace = await this.#key();
442
- await this.#db.batch([this.#db.update(workspaces).set({ deleted: true }).where(eq(workspaces.workspace, workspace)), this.#db.delete(refs).where(eq(refs.workspace, workspace))]);
443
- const catalog = await this.#db.select().from(objects).where(eq(objects.workspace, workspace));
444
- for (const object of catalog) await this.#removeObject(`${workspace}/sha256/${object.digest}`);
874
+ const index = await this.#index();
875
+ const blob = await this.#blob();
876
+ await index.tombstone(workspace);
877
+ for (const key of await index.objects(workspace)) await this.#removeObject(`${workspace}/sha256/${key}`);
445
878
  let cursor;
446
879
  const cursors = /* @__PURE__ */ new Set();
447
880
  const remaining = [];
448
881
  do {
449
- const [error, page] = await this.options.blob.list({
882
+ const [error, page] = await blob.list({
450
883
  prefix: `${workspace}/sha256/`,
451
884
  cursor,
452
885
  limit: 1e3
@@ -458,14 +891,10 @@ var ContentAddressedWorkspaceStore = class {
458
891
  if (cursor) cursors.add(cursor);
459
892
  } while (cursor);
460
893
  for (let offset = 0; offset < remaining.length; offset += 1e3) {
461
- const [error] = await this.options.blob.delete(remaining.slice(offset, offset + 1e3));
894
+ const [error] = await blob.delete(remaining.slice(offset, offset + 1e3));
462
895
  if (error) throw error;
463
896
  }
464
- await this.#db.batch([
465
- this.#db.delete(revisions).where(eq(revisions.workspace, workspace)),
466
- this.#db.delete(objects).where(eq(objects.workspace, workspace)),
467
- this.#db.delete(metadata).where(eq(metadata.workspace, workspace))
468
- ]);
897
+ await index.purge(workspace);
469
898
  this.#draft = void 0;
470
899
  this.#dirty = false;
471
900
  }
@@ -579,28 +1008,28 @@ var ContentAddressedWorkspaceStore = class {
579
1008
  return diffSnapshots(baseline, await createSnapshotFromEntries(await draft.store.list("", { recursive: true })));
580
1009
  }
581
1010
  async getMeta(key) {
582
- const workspace = await this.#key();
583
- const [row] = await this.#db.select().from(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key), this.#active(workspace)));
584
- return row?.value;
1011
+ return await (await this.#index()).getMeta(await this.#key(), key);
585
1012
  }
586
1013
  async setMeta(key, value) {
587
1014
  await this.#assertActive();
588
1015
  const workspace = await this.#key();
589
- if (value === void 0) {
590
- await this.#db.delete(metadata).where(and(eq(metadata.workspace, workspace), eq(metadata.key, key)));
591
- return;
592
- }
593
- await this.#db.insert(metadata).select(this.#db.select({
594
- workspace: sql`${workspace}`.as("workspace"),
595
- key: sql`${key}`.as("key"),
596
- value: sql`${JSON.stringify(value)}`.as("value")
597
- }).from(workspaces).where(and(eq(workspaces.workspace, workspace), eq(workspaces.deleted, false)))).onConflictDoUpdate({
598
- target: [metadata.workspace, metadata.key],
599
- set: { value: sql`${JSON.stringify(value)}` }
600
- });
1016
+ const index = await this.#index();
1017
+ if (value === void 0) await index.deleteMeta(workspace, key);
1018
+ else await index.setMeta(workspace, key, value);
601
1019
  }
602
1020
  };
603
- /** Blob stores bytes; Database atomically publishes immutable folder manifests. */
1021
+ function isSqliteDatabase(value) {
1022
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "batch") === "function";
1023
+ }
1024
+ async function useNamedDatabase() {
1025
+ const { useDatabase } = await import("@vite-hub/database/runtime/registry");
1026
+ return useDatabase;
1027
+ }
1028
+ async function useBlobStore(name) {
1029
+ const { blob } = await import("@vite-hub/blob");
1030
+ return name === "default" ? blob : blob.store(name);
1031
+ }
1032
+ /** Blob stores bytes. The Database publishes immutable folder manifests and rejects a commit from a stale head. */
604
1033
  function createBlobDatabaseWorkspaceStore(options) {
605
1034
  return new ContentAddressedWorkspaceStore(options);
606
1035
  }